<template>
  <div class="app-container">
    <el-page-header content="电子地图" @back="goBack" />
    
    <!-- 操作提示 -->
    <el-alert
      v-if="drawingMode"
      :title="getDrawingTip()"
      type="info"
      :closable="false"
      style="margin-bottom: 10px;"
    />
    
    <!-- 地图加载状态 -->
    <el-alert
      v-if="!mapReady"
      title="地图正在加载中..."
      type="warning"
      :closable="false"
      style="margin-bottom: 10px;"
    />
    
    <!-- 地图搜索框 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索地点（支持拼音、简写，如：北京、bj、天安门）"
        class="search-input"
        @keyup.enter="searchLocation"
        @input="onSearchInput"
        :disabled="!mapReady"
        :loading="isSearching"
        clearable
      >
        <el-button slot="append" icon="el-icon-search" @click="searchLocation" :disabled="!mapReady || !searchKeyword.trim()" :loading="isSearching"></el-button>
      </el-input>
      
      <!-- 搜索建议下拉列表 -->
      <div v-if="searchSuggestions.length > 0 && showSuggestions" class="search-suggestions">
        <div class="suggestion-header">
          <span>搜索建议</span>
          <el-button type="text" size="mini" @click="closeSuggestions">
            <i class="el-icon-close"></i>
          </el-button>
        </div>
        <div 
          v-for="(suggestion, index) in searchSuggestions" 
          :key="index" 
          class="suggestion-item"
          @click="selectSuggestion(suggestion)"
        >
          <div class="suggestion-name" v-html="highlightMatch(suggestion.name, searchKeyword)"></div>
          <div class="suggestion-address">{{ suggestion.address }}</div>
          <div class="suggestion-tags" v-if="suggestion.tags.length > 0">
            <span v-for="tag in suggestion.tags" :key="tag" class="tag">{{ tag }}</span>
          </div>
        </div>
      </div>
      
      <!-- 快捷城市按钮 -->
      <div class="quick-cities" v-if="!isSearching && searchResults.length === 0 && !showSuggestions">
        <span class="quick-label">快速定位：</span>
        <el-button-group size="mini">
          <el-button @click="quickSearch('北京')" :disabled="!mapReady">北京</el-button>
          <el-button @click="quickSearch('上海')" :disabled="!mapReady">上海</el-button>
          <el-button @click="quickSearch('广州')" :disabled="!mapReady">广州</el-button>
          <el-button @click="quickSearch('深圳')" :disabled="!mapReady">深圳</el-button>
          <el-button @click="quickSearch('杭州')" :disabled="!mapReady">杭州</el-button>
        </el-button-group>
      </div>
      
      <!-- 搜索历史 -->
      <div v-if="searchHistory.length > 0 && showSearchHistory && !showSuggestions && searchKeyword === ''" class="search-history">
        <div class="history-header">
          <span>搜索历史</span>
          <el-button type="text" size="mini" @click="clearSearchHistory">
            <i class="el-icon-delete"></i> 清除
          </el-button>
        </div>
        <div class="history-items">
          <el-tag
            v-for="(item, index) in searchHistory.slice(0, 10)"
            :key="index"
            size="mini"
            type="info"
            @click="selectHistoryItem(item)"
            @close="removeHistoryItem(index)"
            closable
            class="history-tag"
          >
            {{ item }}
          </el-tag>
        </div>
      </div>
      
      <!-- 搜索结果下拉列表 -->
      <div v-if="searchResults.length > 0" class="search-results">
        <div 
          v-for="(result, index) in searchResults" 
          :key="index" 
          class="search-result-item"
          @click="selectSearchResult(result)"
        >
          <div class="result-name">{{ result.name }}</div>
          <div class="result-address">{{ result.address }}</div>
        </div>
      </div>
    </div>

    <!-- 地图容器 -->
    <div class="map-container">
      <div id="map" style="width: 100%; height: 500px;"></div>

      <!-- 地图工具栏 -->
      <div class="map-toolbar">
        <div class="toolbar-group">
          <el-tooltip content="放大地图" placement="left">
            <el-button size="mini" icon="el-icon-zoom-in" @click="zoomIn" :disabled="!mapReady"></el-button>
          </el-tooltip>
          <el-tooltip content="缩小地图" placement="left">
            <el-button size="mini" icon="el-icon-zoom-out" @click="zoomOut" :disabled="!mapReady"></el-button>
          </el-tooltip>
        </div>

        <div class="toolbar-group">
          <el-tooltip content="适应所有围栏" placement="left">
            <el-button size="mini" icon="el-icon-full-screen" @click="fitAllFences" :disabled="!mapReady || form.fences.length === 0"></el-button>
          </el-tooltip>
          <el-tooltip content="回到初始位置" placement="left">
            <el-button size="mini" icon="el-icon-location-outline" @click="resetMapView" :disabled="!mapReady"></el-button>
          </el-tooltip>
        </div>

        <div class="toolbar-group">
          <el-tooltip content="测量距离" placement="left">
            <el-button
              size="mini"
              icon="el-icon-ruler"
              :type="measureMode ? 'primary' : 'default'"
              @click="toggleMeasure"
              :disabled="!mapReady"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="清除测量" placement="left">
            <el-button size="mini" icon="el-icon-delete" @click="clearMeasure" :disabled="!mapReady"></el-button>
          </el-tooltip>
        </div>
      </div>

      <!-- 地图信息面板 -->
      <div class="map-info-panel" v-if="mapReady">
        <div class="info-item">
          <span class="info-label">缩放级别:</span>
          <span class="info-value">{{ currentZoom }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">中心坐标:</span>
          <span class="info-value">{{ mapCenter }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">围栏数量:</span>
          <span class="info-value">{{ form.fences.length }}</span>
        </div>
      </div>
    </div>
    
    <!-- 地图工具栏 -->
    <div class="map-toolbar">
      <el-button-group size="small">
        <!-- <el-button @click="startDrawing('circle')" :type="drawingMode === 'circle' ? 'primary' : 'default'" :disabled="!mapReady">
          <i class="el-icon-aim"></i> 点击绘制圆形
        </el-button> -->
        <el-button @click="startDrawing('rectangle')" :type="drawingMode === 'rectangle' ? 'primary' : 'default'" :disabled="!mapReady">
          <i class="el-icon-crop"></i> 点击绘制矩形
        </el-button>
        <el-button @click="clearOverlayOnly" type="warning" :disabled="!mapReady">
          <i class="el-icon-delete"></i> 清除
        </el-button>
        <el-button @click="cancelDrawing" v-if="drawingMode" :disabled="!mapReady">
          <i class="el-icon-close"></i> 取消绘制
        </el-button>
        <el-button @click="testMapLocation" type="info" size="mini" :disabled="!mapReady">
          <i class="el-icon-location"></i> 测试定位
        </el-button>
        <el-button
          @click="toggleFenceLabels"
          :type="showFenceLabels ? 'primary' : 'default'"
          size="mini"
          :disabled="!mapReady"
        >
          <i class="el-icon-price-tag"></i> {{ showFenceLabels ? '隐藏标签' : '显示标签' }}
        </el-button>
        <el-button
          @click="showAllFenceLabels"
          type="success"
          size="mini"
          :disabled="!mapReady || form.fences.length === 0"
        >
          <i class="el-icon-refresh"></i> 刷新标签
        </el-button>
        <el-button
          @click="debugLabels"
          type="warning"
          size="mini"
          :disabled="!mapReady"
        >
          <i class="el-icon-info"></i> 调试标签
        </el-button>
        <el-button
          @click="testFenceCreation"
          type="info"
          size="mini"
          :disabled="!mapReady"
        >
          <i class="el-icon-circle-plus"></i> 测试围栏
        </el-button>
        <el-button
          @click="showPreciseDrawDialog"
          type="success"
          size="mini"
          :disabled="!mapReady"
        >
          <i class="el-icon-edit-outline"></i> 精确绘制
        </el-button>
        <el-button
          @click="loadFenceListFromServer"
          type="primary"
          size="mini"
          :disabled="!mapReady"
          :loading="loadingFenceList"
        >
          <i class="el-icon-refresh"></i> 重新加载围栏
        </el-button>
      </el-button-group>
      
      <!-- 调试信息 -->
      <div class="debug-info" v-if="true">
        <span class="debug-label">状态:</span>
        <span class="debug-value">地图就绪: {{ mapReady ? '是' : '否' }}</span>
        <span class="debug-value">绘制模式: {{ drawingMode || '无' }}</span>
        <span class="debug-value">围栏数量: {{ form.fences.length }}</span>
        <span class="debug-value">搜索状态: {{ isSearching ? '搜索中' : '空闲' }}</span>
      </div>
    </div>
    
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin-top: 20px;">
      <!-- <el-form-item label="围栏名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入围栏名称" />
      </el-form-item> -->
      
      <!-- 围栏列表 -->
      <el-form-item label="围栏列表">
        <div v-if="form.fences.length === 0" class="no-fences">
          <el-alert title="暂无围栏，请在地图上绘制围栏" type="info" :closable="false" />
        </div>
        
        <div v-else class="fence-table-container" 
             ref="fenceTableContainer"
             @mousedown="startTableDrag"
             @mousemove="onTableDrag"
             @mouseup="stopTableDrag"
             @mouseleave="stopTableDrag">
          <el-table 
            :data="form.fences" 
            border 
            size="small"
            :row-class-name="getRowClassName"
            @row-click="onRowClick"
            style="width: 100%"
            max-height="350"
            @selection-change="onFenceSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>

            <!-- 围栏名称列 -->
            <el-table-column prop="name" label="围栏名称" min-width="150">
              <template slot-scope="scope">
                <div class="fence-name-cell">
                  <span v-if="!scope.row.editingName" 
                        class="fence-name-display"
                        @dblclick="startEditName(scope.row)"
                        :title="'双击编辑名称'">
                    {{ scope.row.name }}
                  </span>
                  <div v-else class="fence-name-edit-inline">
                    <el-input
                      v-model="scope.row.tempName"
                      size="mini"
                      @keyup.enter="saveNameEdit(scope.row)"
                      @keyup.esc="cancelNameEdit(scope.row)"
                      ref="nameInput"
                      placeholder="请输入围栏名称"
                    />
                    <div class="edit-actions-inline">
                      <el-button size="mini" type="text" @click="saveNameEdit(scope.row)">
                        <i class="el-icon-check" style="color: #67C23A;"></i>
                      </el-button>
                      <el-button size="mini" type="text" @click="cancelNameEdit(scope.row)">
                        <i class="el-icon-close" style="color: #F56C6C;"></i>
                      </el-button>
                    </div>
                  </div>
                  <span class="fence-type-tag">{{ getFenceTypeText(scope.row.type) }}</span>
                </div>
              </template>
            </el-table-column>

            <!-- 中心位置列 -->
            <el-table-column label="中心位置（经纬度）" min-width="180">
              <template slot-scope="scope">
                <div class="location-cell">
                  <div class="coordinate-item">
                    <span class="coordinate-label">经度:</span>
                    <span class="coordinate-value">{{ scope.row.centerLng.toFixed(6) }}</span>
                  </div>
                  <div class="coordinate-item">
                    <span class="coordinate-label">纬度:</span>
                    <span class="coordinate-value">{{ scope.row.centerLat.toFixed(6) }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>

            <!-- 围栏大小列 -->
            <el-table-column label="围栏大小" min-width="140">
              <template slot-scope="scope">
                <div class="fence-size-cell">
                  <span v-if="!scope.row.editingParams" 
                        class="size-display"
                        @dblclick="startEditParams(scope.row)"
                        :title="'双击编辑参数'">
                    {{ getFenceSizeText(scope.row) }}
                  </span>
                  <div v-else class="size-edit-inline">
                    <!-- 圆形围栏参数编辑 -->
                    <div v-if="scope.row.type === 'circle'" class="param-edit-inline">
                      <el-input-number
                        v-model="scope.row.tempRadius"
                        size="mini"
                        :min="10"
                        :max="10000"
                        :step="10"
                        placeholder="半径(米)"
                        controls-position="right"
                      />
                    </div>
                    <!-- 矩形围栏参数编辑 -->
                    <div v-else-if="scope.row.type === 'rectangle'" class="param-edit-inline">
                      <el-input-number
                        v-model="scope.row.tempWidth"
                        size="mini"
                        :min="10"
                        :max="10000"
                        :step="10"
                        placeholder="宽度(米)"
                        controls-position="right"
                        style="margin-bottom: 5px;"
                      />
                      <el-input-number
                        v-model="scope.row.tempHeight"
                        size="mini"
                        :min="10"
                        :max="10000"
                        :step="10"
                        placeholder="高度(米)"
                        controls-position="right"
                      />
                    </div>
                    <div class="edit-actions-inline">
                      <el-button size="mini" type="text" @click="saveParamsEdit(scope.row)">
                        <i class="el-icon-check" style="color: #67C23A;"></i>
                      </el-button>
                      <el-button size="mini" type="text" @click="cancelParamsEdit(scope.row)">
                        <i class="el-icon-close" style="color: #F56C6C;"></i>
                      </el-button>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <div class="fence-actions-cell">
                  <el-button 
                    size="mini" 
                    type="primary"
                    icon="el-icon-location"
                    @click.stop="focusFence(scope.row)"
                    title="定位到围栏">
                    定位
                  </el-button>
                  <el-button 
                    size="mini" 
                    type="danger"
                    icon="el-icon-delete"
                    @click.stop="deleteFence(scope.$index)"
                    title="删除围栏">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 围栏统计信息 -->
          <div class="fence-summary">
            <el-tag size="small" type="info">
              总计：{{ form.fences.length }} 个围栏
            </el-tag>
            <el-tag v-if="selectedFenceId" size="small" type="warning">
              已选中：{{ getSelectedFenceName() }}
            </el-tag>
          </div>
        </div>
      </el-form-item>
      
      <!-- <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="围栏描述信息" />
      </el-form-item> -->
      
      <el-form-item>
        <el-button type="primary" @click="submit" :loading="submitting">提交更新</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>

    <!-- 精确绘制对话框 -->
    <el-dialog
      title="精确绘制围栏"
      :visible.sync="preciseDrawDialog"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="preciseForm" :model="preciseForm" :rules="preciseRules" label-width="100px">
        <el-form-item label="围栏类型" prop="type">
          <el-radio-group v-model="preciseForm.type">
            <el-radio label="circle">圆形围栏</el-radio>
            <el-radio label="rectangle">矩形围栏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="围栏名称" prop="name">
          <el-input v-model="preciseForm.name" placeholder="请输入围栏名称" />
        </el-form-item>

        <el-form-item label="中心经度" prop="centerLng">
          <el-input-number
            v-model="preciseForm.centerLng"
            :precision="6"
            :step="0.000001"
            :min="-180"
            :max="180"
            style="width: 100%"
            placeholder="请输入中心点经度"
          />
        </el-form-item>

        <el-form-item label="中心纬度" prop="centerLat">
          <el-input-number
            v-model="preciseForm.centerLat"
            :precision="6"
            :step="0.000001"
            :min="-90"
            :max="90"
            style="width: 100%"
            placeholder="请输入中心点纬度"
          />
        </el-form-item>

        <!-- 圆形围栏参数 -->
        <el-form-item v-if="preciseForm.type === 'circle'" label="半径(米)" prop="radius">
          <el-input-number
            v-model="preciseForm.radius"
            :min="10"
            :max="10000"
            :step="10"
            style="width: 100%"
            placeholder="请输入围栏半径"
          />
        </el-form-item>

        <!-- 矩形围栏参数 -->
        <template v-if="preciseForm.type === 'rectangle'">
          <el-form-item label="宽度(米)" prop="width">
            <el-input-number
              v-model="preciseForm.width"
              :min="10"
              :max="10000"
              :step="10"
              style="width: 100%"
              placeholder="请输入围栏宽度"
            />
          </el-form-item>

          <el-form-item label="高度(米)" prop="height">
            <el-input-number
              v-model="preciseForm.height"
              :min="10"
              :max="10000"
              :step="10"
              style="width: 100%"
              placeholder="请输入围栏高度"
            />
          </el-form-item>
        </template>

        <el-form-item>
          <el-button @click="previewPreciseFence" type="info">预览</el-button>
          <el-button @click="getCurrentLocation" type="warning">获取当前位置</el-button>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="preciseDrawDialog = false">取消</el-button>
        <el-button type="primary" @click="createPreciseFence" :loading="creatingPreciseFence">创建围栏</el-button>
      </div>
    </el-dialog>

    <!-- 围栏名称输入对话框 -->
    <el-dialog
      title="输入围栏名称"
      :visible.sync="fenceNameDialog"
      width="400px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form ref="fenceNameForm" :model="fenceNameForm" :rules="fenceNameRules" label-width="80px">
        <el-form-item label="围栏名称" prop="name">
          <el-input
            v-model="fenceNameForm.name"
            placeholder="请输入围栏名称，留空将自动生成"
            @keyup.enter="confirmFenceName"
            ref="fenceNameInput"
          />
        </el-form-item>
        <div class="name-tips">
          <p><i class="el-icon-info"></i> 提示：</p>
          <ul>
            <li>• 如果不输入名称，系统将自动生成（如：圆形围栏1）</li>
            <li>• 建议使用有意义的名称，便于管理和识别</li>
            <li>• 名称长度限制在50个字符以内</li>
          </ul>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFenceNaming">取消绘制</el-button>
        <el-button @click="skipFenceNaming">跳过命名</el-button>
        <el-button type="primary" @click="confirmFenceName">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryFences, queryFenceById, createFence, updateFence, deleteFence } from '@/api/fence'

export default {
  name: 'FenceUpdate',
  data() {
    return {
      form: {
        id: null,
        name: '',
        description: '',
        fences: [] // 改为数组，支持多个围栏
      },
      // 围栏标签显示控制
      showFenceLabels: true,
      fenceLabels: [], // 存储围栏标签
      // 围栏名称输入
      fenceNameDialog: false,
      pendingFenceData: null, // 待命名的围栏数据
      fenceNameForm: {
        name: ''
      },
      fenceNameRules: {
        name: [
          { required: true, message: '请输入围栏名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      // 精确绘制相关
      preciseDrawDialog: false,
      creatingPreciseFence: false,
      preciseForm: {
        type: 'circle',
        name: '',
        centerLng: 116.397428,
        centerLat: 39.90923,
        radius: 200,
        width: 100,
        height: 100
      },
      preciseRules: {
        name: [
          { required: true, message: '请输入围栏名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        centerLng: [
          { required: true, message: '请输入中心经度', trigger: 'blur' },
          { type: 'number', min: -180, max: 180, message: '经度范围为-180到180', trigger: 'blur' }
        ],
        centerLat: [
          { required: true, message: '请输入中心纬度', trigger: 'blur' },
          { type: 'number', min: -90, max: 90, message: '纬度范围为-90到90', trigger: 'blur' }
        ],
        radius: [
          { required: true, message: '请输入围栏半径', trigger: 'blur' },
          { type: 'number', min: 10, max: 10000, message: '半径范围为10到10000米', trigger: 'blur' }
        ],
        width: [
          { required: true, message: '请输入围栏宽度', trigger: 'blur' },
          { type: 'number', min: 10, max: 10000, message: '宽度范围为10到10000米', trigger: 'blur' }
        ],
        height: [
          { required: true, message: '请输入围栏高度', trigger: 'blur' },
          { type: 'number', min: 10, max: 10000, message: '高度范围为10到10000米', trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入围栏名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      },
      map: null,
      T: null, // 天地图对象
      overlays: [], // 改为数组，存储多个覆盖物
      submitting: false,
      drawingMode: null, // 当前绘制模式: 'circle', 'rectangle', null
      mapReady: false, // 地图是否准备就绪
      searchKeyword: '', // 搜索关键词
      searchResults: [], // 搜索结果
      searchMarker: null, // 搜索结果标记
      isSearching: false, // 是否正在搜索
      selectedFenceId: null, // 当前选中的围栏ID
      searchSuggestions: [], // 搜索建议
      showSuggestions: false, // 是否显示搜索建议
      showSearchHistory: false, // 是否显示搜索历史
      searchHistory: JSON.parse(localStorage.getItem('searchHistory') || '[]'), // 搜索历史
      searchDebounceTimer: null, // 搜索防抖定时器
      placeDatabase: [], // 扩展的地点数据库
      // 地图交互相关
      currentZoom: 12,
      mapCenter: '116.397428, 39.90923',
      measureMode: false,
      measureOverlays: [], // 测量覆盖物
      isRerendering: false, // 是否正在重新渲染
      loadingFenceList: false, // 是否正在加载围栏列表
      // 表格拖拽相关
      tableDragging: false, // 是否正在拖拽表格
      dragStartX: 0, // 拖拽开始时的X坐标
      dragStartScrollLeft: 0 // 拖拽开始时的滚动位置
    }
  },
  async mounted() {
    // 先加载围栏数据
    await this.loadFenceData()
    
    // 然后加载地图
    this.loadTiandituAPI().then(() => {
      this.initMap()
      // 如果URL中没有ID参数，则加载围栏列表
      if (!this.$route.params.id) {
        this.loadFenceList()
      }
    }).catch(error => {
      console.error('天地图API加载失败:', error)
      this.$message.error('地图加载失败，请检查网络连接')
    })
    
    // 初始化扩展地点数据库
    this.initPlaceDatabase()
    
    // 监听点击事件，关闭搜索建议
    document.addEventListener('click', this.handleDocumentClick)
  },
  beforeDestroy() {
    this.clearAllOverlays()
    this.clearSearchMarker()
    
    // 清理定时器和事件监听器
    if (this.searchDebounceTimer) {
      clearTimeout(this.searchDebounceTimer)
    }
    document.removeEventListener('click', this.handleDocumentClick)
  },
  methods: {
    // 初始化扩展地点数据库
    initPlaceDatabase() {
      this.placeDatabase = [
        // 主要城市
        { 
          name: '北京', 
          address: '北京市', 
          lng: 116.4074, 
          lat: 39.9042, 
          aliases: ['北京市', 'bj', 'BJ', 'beijing', 'BEIJING'], 
          tags: ['直辖市', '首都'],
          type: 'city'
        },
        { 
          name: '上海', 
          address: '上海市', 
          lng: 121.4737, 
          lat: 31.2304, 
          aliases: ['上海市', 'sh', 'SH', 'shanghai', 'SHANGHAI'], 
          tags: ['直辖市', '经济中心'],
          type: 'city'
        },
        { 
          name: '广州', 
          address: '广东省广州市', 
          lng: 113.2644, 
          lat: 23.1291, 
          aliases: ['广州市', 'gz', 'GZ', 'guangzhou', 'GUANGZHOU'], 
          tags: ['省会', '广东'],
          type: 'city'
        },
        { 
          name: '深圳', 
          address: '广东省深圳市', 
          lng: 114.0579, 
          lat: 22.5431, 
          aliases: ['深圳市', 'sz', 'SZ', 'shenzhen', 'SHENZHEN'], 
          tags: ['特区', '广东'],
          type: 'city'
        },
        { 
          name: '杭州', 
          address: '浙江省杭州市', 
          lng: 120.1551, 
          lat: 30.2741, 
          aliases: ['杭州市', 'hz', 'HZ', 'hangzhou', 'HANGZHOU'], 
          tags: ['省会', '浙江'],
          type: 'city'
        },
        { 
          name: '南京', 
          address: '江苏省南京市', 
          lng: 118.7969, 
          lat: 32.0603, 
          aliases: ['南京市', 'nj', 'NJ', 'nanjing', 'NANJING'], 
          tags: ['省会', '江苏'],
          type: 'city'
        },
        { 
          name: '武汉', 
          address: '湖北省武汉市', 
          lng: 114.3054, 
          lat: 30.5931, 
          aliases: ['武汉市', 'wh', 'WH', 'wuhan', 'WUHAN'], 
          tags: ['省会', '湖北'],
          type: 'city'
        },
        { 
          name: '成都', 
          address: '四川省成都市', 
          lng: 104.0665, 
          lat: 30.5723, 
          aliases: ['成都市', 'cd', 'CD', 'chengdu', 'CHENGDU'], 
          tags: ['省会', '四川'],
          type: 'city'
        },
        { 
          name: '西安', 
          address: '陕西省西安市', 
          lng: 108.9402, 
          lat: 34.3416, 
          aliases: ['西安市', 'xa', 'XA', 'xian', 'XIAN'], 
          tags: ['省会', '陕西'],
          type: 'city'
        },
        { 
          name: '重庆', 
          address: '重庆市', 
          lng: 106.5516, 
          lat: 29.5630, 
          aliases: ['重庆市', 'cq', 'CQ', 'chongqing', 'CHONGQING'], 
          tags: ['直辖市'],
          type: 'city'
        },
        // 知名地标
        { 
          name: '天安门', 
          address: '北京市东城区天安门广场', 
          lng: 116.3972, 
          lat: 39.9097, 
          aliases: ['天安门广场', '天安门城楼', 'tam', 'tiananmen', '安门', '天门'], 
          tags: ['地标', '北京', '广场', '历史'],
          type: 'landmark'
        },
        { 
          name: '故宫', 
          address: '北京市东城区故宫博物院', 
          lng: 116.3979, 
          lat: 39.9163, 
          aliases: ['紫禁城', '故宫博物院', 'gugong', 'forbidden city'], 
          tags: ['地标', '北京', '博物馆', '历史'],
          type: 'landmark'
        },
        { 
          name: '外滩', 
          address: '上海市黄浦区外滩', 
          lng: 121.4906, 
          lat: 31.2397, 
          aliases: ['上海外滩', 'waitan', 'the bund', '黄浦江外滩'], 
          tags: ['地标', '上海', '江景'],
          type: 'landmark'
        },
        { 
          name: '东方明珠', 
          address: '上海市浦东新区东方明珠塔', 
          lng: 121.4995, 
          lat: 31.2397, 
          aliases: ['东方明珠塔', 'oriental pearl', 'dongfangmingzhu'], 
          tags: ['地标', '上海', '塔'],
          type: 'landmark'
        },
        { 
          name: '小蛮腰', 
          address: '广州市海珠区广州塔', 
          lng: 113.3191, 
          lat: 23.1056, 
          aliases: ['广州塔', 'canton tower', 'xmy', '广州电视塔'], 
          tags: ['地标', '广州', '塔'],
          type: 'landmark'
        },
        { 
          name: '西湖', 
          address: '浙江省杭州市西湖区西湖', 
          lng: 120.1507, 
          lat: 30.2547, 
          aliases: ['杭州西湖', 'xihu', 'west lake', '西子湖'], 
          tags: ['景点', '杭州', '湖泊'],
          type: 'scenic'
        },
        { 
          name: '长城', 
          address: '北京市延庆区八达岭长城', 
          lng: 116.0085, 
          lat: 40.3590, 
          aliases: ['万里长城', '八达岭长城', 'great wall', 'changcheng'], 
          tags: ['地标', '北京', '历史', '世界遗产'],
          type: 'landmark'
        },
        { 
          name: '鸟巢', 
          address: '北京市朝阳区国家体育场', 
          lng: 116.3973, 
          lat: 39.9934, 
          aliases: ['国家体育场', 'bird nest', 'niaochao', '体育场'], 
          tags: ['地标', '北京', '体育', '奥运'],
          type: 'landmark'
        },
        { 
          name: '水立方', 
          address: '北京市朝阳区国家游泳中心', 
          lng: 116.3894, 
          lat: 39.9920, 
          aliases: ['国家游泳中心', 'water cube', 'shulifang'], 
          tags: ['地标', '北京', '体育', '奥运'],
          type: 'landmark'
        }
      ]
      
      console.log('地点数据库初始化完成，共载入', this.placeDatabase.length, '个地点')
    },
    
    // 搜索输入事件处理
    onSearchInput(value) {
      // 清除之前的定时器
      if (this.searchDebounceTimer) {
        clearTimeout(this.searchDebounceTimer)
      }
      
      // 如果输入为空，显示搜索历史
      if (!value.trim()) {
        this.searchSuggestions = []
        this.showSuggestions = false
        this.showSearchHistory = this.searchHistory.length > 0
        return
      }
      
      // 设置防抖延迟
      this.searchDebounceTimer = setTimeout(() => {
        this.generateSuggestions(value)
      }, 300)
    },
    
    // 生成搜索建议
    generateSuggestions(keyword) {
      if (!keyword || keyword.trim().length === 0) {
        this.searchSuggestions = []
        this.showSuggestions = false
        return
      }
      
      const normalizedKeyword = keyword.toLowerCase().trim()
      const suggestions = []
      
      console.log('开始生成搜索建议，关键词:', normalizedKeyword, '数据库条目:', this.placeDatabase.length)
      
      // 模糊匹配算法
      this.placeDatabase.forEach(place => {
        const score = this.calculateMatchScore(place, normalizedKeyword)
        console.log(`地点 ${place.name} 匹配分数:`, score)
        if (score > 0) {
          suggestions.push({
            ...place,
            score: score
          })
        }
      })
      
      // 按匹配度排序
      suggestions.sort((a, b) => b.score - a.score)
      
      // 最多显示8个建议
      this.searchSuggestions = suggestions.slice(0, 8)
      this.showSuggestions = this.searchSuggestions.length > 0
      this.showSearchHistory = false
      
      console.log('生成搜索建议完成:', this.searchSuggestions.length, '个结果', this.searchSuggestions.map(s => s.name))
      
      // 如果没有找到任何匹配，提供一些智能建议
      if (this.searchSuggestions.length === 0) {
        this.provideSmartSuggestions(normalizedKeyword)
      }
    },
    
    // 提供智能建议
    provideSmartSuggestions(keyword) {
      console.log('提供智能建议，关键词:', keyword)
      
      // 根据关键词特征推荐相关地点
      const smartSuggestions = []
      
      // 如果包含"天"、"门"等字符，推荐天安门
      if (keyword.includes('天') || keyword.includes('门') || keyword.includes('安')) {
        const tiananmen = this.placeDatabase.find(p => p.name === '天安门')
        if (tiananmen) {
          smartSuggestions.push({ ...tiananmen, score: 95 })
        }
      }
      
      // 如果包含"外"、"滩"等字符，推荐外滩
      if (keyword.includes('外') || keyword.includes('滩') || keyword.includes('上海')) {
        const waitan = this.placeDatabase.find(p => p.name === '外滩')
        if (waitan) {
          smartSuggestions.push({ ...waitan, score: 95 })
        }
      }
      
      // 如果包含"西"、"湖"等字符，推荐西湖
      if (keyword.includes('西') || keyword.includes('湖') || keyword.includes('杭州')) {
        const xihu = this.placeDatabase.find(p => p.name === '西湖')
        if (xihu) {
          smartSuggestions.push({ ...xihu, score: 95 })
        }
      }
      
      // 如果没有智能匹配，显示热门推荐
      if (smartSuggestions.length === 0) {
        const hotPlaces = ['天安门', '外滩', '西湖', '广州塔'].map(name => {
          const place = this.placeDatabase.find(p => p.name === name)
          return place ? { ...place, score: 80 } : null
        }).filter(Boolean)
        
        smartSuggestions.push(...hotPlaces)
      }
      
      if (smartSuggestions.length > 0) {
        this.searchSuggestions = smartSuggestions.slice(0, 6)
        this.showSuggestions = true
        console.log('智能建议结果:', this.searchSuggestions.map(s => s.name))
      }
    },
    
    // 计算匹配分数
    calculateMatchScore(place, keyword) {
      let score = 0
      const name = place.name.toLowerCase()
      const address = place.address.toLowerCase()
      const keywordLower = keyword.toLowerCase()
      
      // 精确匹配得分最高
      if (name === keywordLower) {
        score += 100
      } else if (name.includes(keywordLower)) {
        score += 80
      } else if (address.includes(keywordLower)) {
        score += 60
      }
      
      // 别名匹配
      place.aliases.forEach(alias => {
        const aliasLower = alias.toLowerCase()
        if (aliasLower === keywordLower) {
          score += 90
        } else if (aliasLower.includes(keywordLower)) {
          score += 70
        }
      })
      
      // 标签匹配
      place.tags.forEach(tag => {
        const tagLower = tag.toLowerCase()
        if (tagLower.includes(keywordLower)) {
          score += 40
        }
      })
      
      // 拼音首字母匹配
      if (this.matchPinyin(name, keywordLower)) {
        score += 50
      }
      
      // 模糊包含匹配（处理部分字符匹配）
      if (this.fuzzyContains(name, keywordLower)) {
        score += 30
      }
      
      if (this.fuzzyContains(address, keywordLower)) {
        score += 25
      }
      
      // 检查别名的模糊匹配
      place.aliases.forEach(alias => {
        if (this.fuzzyContains(alias.toLowerCase(), keywordLower)) {
          score += 35
        }
      })
      
      return score
    },
    
    // 简单的拼音首字母匹配
    matchPinyin(name, keyword) {
      const pinyinMap = {
        '北': 'b', '京': 'j', '上': 's', '海': 'h', '广': 'g', '州': 'z',
        '深': 's', '圳': 'z', '杭': 'h', '南': 'n', '武': 'w', '汉': 'h',
        '成': 'c', '都': 'd', '西': 'x', '安': 'a', '重': 'c', '庆': 'q',
        '天': 't', '门': 'm', '外': 'w', '滩': 't', '小': 'x', '蛮': 'm',
        '腰': 'y', '湖': 'h', '市': 's', '省': 's', '区': 'q', '县': 'x',
        '镇': 'z', '村': 'c', '路': 'l', '街': 'j', '道': 'd', '巷': 'x'
      }
      
      let pinyin = ''
      for (let char of name) {
        if (pinyinMap[char]) {
          pinyin += pinyinMap[char]
        }
      }
      
      return pinyin.includes(keyword)
    },
    
    // 模糊包含匹配
    fuzzyContains(text, keyword) {
      if (!text || !keyword) return false
      
      // 移除空格和特殊字符
      const normalizedText = text.replace(/[\s\-_]/g, '').toLowerCase()
      const normalizedKeyword = keyword.replace(/[\s\-_]/g, '').toLowerCase()
      
      // 如果关键词很短，需要更严格的匹配
      if (normalizedKeyword.length <= 2) {
        return normalizedText.includes(normalizedKeyword)
      }
      
              // 对于较长的关键词，允许一些字符的差异
        let matchCount = 0
        let keywordIndex = 0
        
        for (let i = 0; i < normalizedText.length && keywordIndex < normalizedKeyword.length; i++) {
        if (normalizedText[i] === normalizedKeyword[keywordIndex]) {
          matchCount++
          keywordIndex++
        }
      }
      
      // 至少匹配80%的字符
      return (matchCount / normalizedKeyword.length) >= 0.8
    },
    
    // 高亮匹配文本
    highlightMatch(text, keyword) {
      if (!keyword) return text
      
      const regex = new RegExp(`(${keyword})`, 'gi')
      return text.replace(regex, '<span class="highlight">$1</span>')
    },
    
    // 选择搜索建议
    selectSuggestion(suggestion) {
      console.log('选择搜索建议:', suggestion)
      console.log('地图状态检查 - mapReady:', this.mapReady, 'map:', !!this.map, 'T:', !!this.T)
      
      this.searchKeyword = suggestion.name
      this.searchSuggestions = []
      this.showSuggestions = false
      
      // 添加到搜索历史
      this.addToSearchHistory(suggestion.name)
      
      // 检查地图是否准备就绪
      if (!this.mapReady || !this.map || !this.T) {
        console.warn('地图未准备就绪，延迟执行定位')
        this.$message.warning('地图正在加载中，请稍后再试')
        
        // 等待地图准备就绪后再执行
        const checkMapReady = () => {
          if (this.mapReady && this.map && this.T) {
            console.log('地图准备就绪，执行定位')
            this.selectSearchResult({
              name: suggestion.name,
              address: suggestion.address,
              lng: suggestion.lng,
              lat: suggestion.lat
            })
          } else {
            setTimeout(checkMapReady, 500)
          }
        }
        setTimeout(checkMapReady, 500)
        return
      }
      
      // 直接定位到选择的地点
      this.selectSearchResult({
        name: suggestion.name,
        address: suggestion.address,
        lng: suggestion.lng,
        lat: suggestion.lat
      })
    },
    
    // 关闭搜索建议
    closeSuggestions() {
      this.searchSuggestions = []
      this.showSuggestions = false
    },
    
    // 处理文档点击事件
    handleDocumentClick(e) {
      const searchContainer = this.$el.querySelector('.search-container')
      if (searchContainer && !searchContainer.contains(e.target)) {
        this.showSuggestions = false
        this.showSearchHistory = false
      }
    },
    
    // 添加到搜索历史
    addToSearchHistory(keyword) {
      if (!keyword || keyword.trim() === '') return
      
      // 移除已存在的相同关键词
      const index = this.searchHistory.indexOf(keyword)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      
      // 添加到开头
      this.searchHistory.unshift(keyword)
      
      // 最多保存20个历史记录
      if (this.searchHistory.length > 20) {
        this.searchHistory = this.searchHistory.slice(0, 20)
      }
      
      // 保存到本地存储
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },
    
    // 选择历史记录项
    selectHistoryItem(keyword) {
      this.searchKeyword = keyword
      this.showSearchHistory = false
      this.searchLocation()
    },
    
    // 移除历史记录项
    removeHistoryItem(index) {
      this.searchHistory.splice(index, 1)
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },
    
    // 清除搜索历史
    clearSearchHistory() {
      this.searchHistory = []
      this.showSearchHistory = false
      localStorage.removeItem('searchHistory')
      this.$message.success('搜索历史已清除')
    },
    
    // 加载天地图API
    
    // 加载天地图API - 增强错误处理
    loadTiandituAPI() {
      return new Promise((resolve, reject) => {
        // 检查是否已存在
        if (window.T && window.T.Map && window.T.LngLat) {
          console.log('天地图API已存在')
          this.T = window.T
          resolve()
          return
        }

        console.log('开始加载天地图API...')
        const script = document.createElement('script')

        // 天地图API配置
        const apiConfig = {
          version: '4.0',
          token: 'b5ce37dbd64b3f4a990cb9e90fc0aa1e',
          protocol: location.protocol === 'https:' ? 'https' : 'http'
        }

        script.src = `${apiConfig.protocol}://api.tianditu.gov.cn/api?v=${apiConfig.version}&tk=${apiConfig.token}`

        // 设置超时
        const timeout = setTimeout(() => {
          console.error('天地图API加载超时')
          if (document.head.contains(script)) {
            document.head.removeChild(script)
          }
          reject(new Error('天地图API加载超时'))
        }, 20000) // 增加超时时间到20秒

        script.onload = () => {
          clearTimeout(timeout)
          console.log('天地图API脚本加载完成')

          // 等待API完全初始化
          const checkAPI = () => {
            if (window.T && window.T.Map && window.T.LngLat && window.T.Circle && window.T.Polygon) {
              this.T = window.T
              console.log('天地图API验证通过')
              resolve()
            } else {
              console.log('等待天地图API完全加载...')
              setTimeout(checkAPI, 100)
            }
          }
          checkAPI()
        }

        script.onerror = (error) => {
          clearTimeout(timeout)
          console.error('天地图API加载失败:', error)
          if (document.head.contains(script)) {
            document.head.removeChild(script)
          }
          reject(new Error('天地图API网络加载失败'))
        }

        document.head.appendChild(script)
      })
    },
    // 初始化地图
    initMap() {
      if (!this.T) {
        console.error('天地图对象不存在')
        return
      }
      
      try {
        console.log('开始初始化地图...')
        this.map = new this.T.Map('map')
        this.map.centerAndZoom(new this.T.LngLat(116.397428, 39.90923), 12)
        
        // 添加地图控件
        const ctrl = new this.T.Control.MapType()
        this.map.addControl(ctrl)
        
        const zoomCtrl = new this.T.Control.Zoom()
        this.map.addControl(zoomCtrl)
        
        // 地图点击事件
        this.map.addEventListener('click', this.onMapClick)
        
        // 地图加载完成事件
        this.map.addEventListener('load', () => {
          console.log('地图加载完成')
          this.mapReady = true
          
          // 地图加载完成后，如果有围栏数据则渲染
          this.$nextTick(() => {
            this.renderFenceOnMap()
          })
        })
        
        console.log('地图初始化完成')
        this.mapReady = true
        
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.$message.error('地图初始化失败')
      }
    },
    
    // 搜索地点
    async searchLocation() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键词')
        return
      }
      
      if (!this.mapReady) {
        this.$message.warning('地图尚未准备就绪，请稍后再试')
        return
      }
      
      this.isSearching = true
      this.searchResults = []
      this.searchSuggestions = [] // 清空建议
      this.showSuggestions = false // 隐藏建议
      this.showSearchHistory = false // 隐藏历史
      
      try {
        console.log('开始搜索地点:', this.searchKeyword)
        
        // 使用天地图搜索服务 - 修复API调用
        const tk = 'b5ce37dbd64b3f4a990cb9e90fc0aa1e'
        const keyword = encodeURIComponent(this.searchKeyword)
        
        // 使用JSONP方式调用天地图API，避免跨域问题
        const searchUrl = `https://api.tianditu.gov.cn/geocoder?ds={"keyWord":"${keyword}"}&tk=${tk}`
        
        console.log('搜索URL:', searchUrl)
        
        // 创建JSONP请求
        const script = document.createElement('script')
        const callbackName = 'searchCallback_' + Date.now()
        
        // 创建全局回调函数
        window[callbackName] = (data) => {
          console.log('搜索返回数据:', data)
          
          this.isSearching = false
          
          if (data.status === '0' && data.result && data.result.length > 0) {
            this.searchResults = data.result.map(item => ({
              name: item.name,
              address: item.formatted_address || item.address || '',
              lng: parseFloat(item.location.lon),
              lat: parseFloat(item.location.lat),
              level: item.level || ''
            }))
            
            console.log('处理后的搜索结果:', this.searchResults)
            
            // 如果只有一个结果，直接定位
            if (this.searchResults.length === 1) {
              this.selectSearchResult(this.searchResults[0])
            }
          } else {
            // 如果天地图搜索失败，尝试使用简单的地名匹配
            this.fallbackSearch()
          }
          
          // 清理
          document.head.removeChild(script)
          delete window[callbackName]
        }
        
        script.src = searchUrl + `&callback=${callbackName}`
        script.onerror = () => {
          console.error('天地图API调用失败，使用备用搜索')
          this.fallbackSearch()
          document.head.removeChild(script)
          delete window[callbackName]
        }
        
        document.head.appendChild(script)
        
        // 设置超时
        setTimeout(() => {
          if (this.isSearching) {
            console.log('搜索超时，使用备用方案')
            this.fallbackSearch()
            if (document.head.contains(script)) {
              document.head.removeChild(script)
            }
            if (window[callbackName]) {
              delete window[callbackName]
            }
          }
        }, 5000)
        
      } catch (error) {
        console.error('搜索地点失败:', error)
        this.fallbackSearch()
      }
    },
    
    // 备用搜索方法
    fallbackSearch() {
      this.isSearching = false
      
      const keyword = this.searchKeyword.trim()
      console.log('使用备用搜索:', keyword)
      
      // 首先尝试从本地数据库搜索
      this.generateSuggestions(keyword)
      
      if (this.searchSuggestions.length > 0) {
        // 如果有搜索建议，显示它们
        this.showSuggestions = true
        this.$message.info('已为您推荐相关地点，请从下拉列表中选择')
        return
      }
      
      // 如果本地搜索没有结果，使用简单的地名映射
      const cityCoords = {
        '北京': { lng: 116.4074, lat: 39.9042, name: '北京市', address: '北京市' },
        '上海': { lng: 121.4737, lat: 31.2304, name: '上海市', address: '上海市' },
        '广州': { lng: 113.2644, lat: 23.1291, name: '广州市', address: '广东省广州市' },
        '深圳': { lng: 114.0579, lat: 22.5431, name: '深圳市', address: '广东省深圳市' },
        '杭州': { lng: 120.1551, lat: 30.2741, name: '杭州市', address: '浙江省杭州市' },
        '南京': { lng: 118.7969, lat: 32.0603, name: '南京市', address: '江苏省南京市' },
        '武汉': { lng: 114.3054, lat: 30.5931, name: '武汉市', address: '湖北省武汉市' },
        '成都': { lng: 104.0665, lat: 30.5723, name: '成都市', address: '四川省成都市' },
        '西安': { lng: 108.9402, lat: 34.3416, name: '西安市', address: '陕西省西安市' },
        '重庆': { lng: 106.5516, lat: 29.5630, name: '重庆市', address: '重庆市' }
      }
      
      const results = []
      
      // 查找匹配的城市
      for (const [city, coords] of Object.entries(cityCoords)) {
        if (keyword.includes(city) || city.includes(keyword)) {
          results.push(coords)
        }
      }
      
      if (results.length > 0) {
        this.searchResults = results
        console.log('备用搜索结果:', this.searchResults)
        
        if (results.length === 1) {
          this.selectSearchResult(results[0])
        }
      } else {
        // 显示一些相关的推荐
        this.showRecommendations()
      }
    },
    
    // 显示推荐地点
    showRecommendations() {
      // 显示一些热门地点作为推荐
      const recommendations = [
        { name: '天安门', address: '北京市东城区天安门广场', lng: 116.3972, lat: 39.9097 },
        { name: '外滩', address: '上海市黄浦区外滩', lng: 121.4906, lat: 31.2397 },
        { name: '西湖', address: '浙江省杭州市西湖区西湖', lng: 120.1507, lat: 30.2547 },
        { name: '广州塔', address: '广州市海珠区广州塔', lng: 113.3191, lat: 23.1056 }
      ]
      
      this.searchSuggestions = recommendations.map(place => ({
        ...place,
        aliases: [],
        tags: ['推荐地点'],
        type: 'recommendation'
      }))
      
      this.showSuggestions = true
      this.$message.info('未找到"' + this.searchKeyword + '"，为您推荐以下热门地点')
    },
    
    // 选择搜索结果
    selectSearchResult(result) {
      console.log('选择搜索结果:', result)
      console.log('地图对象状态 - map:', !!this.map, 'T:', !!this.T, 'mapReady:', this.mapReady)
      
      if (!this.map || !this.T || !this.mapReady) {
        console.error('地图未准备就绪')
        this.$message.error('地图未准备就绪，请稍后再试')
        return
      }
      
      // 验证坐标有效性 - 更宽松的检查
      const lng = parseFloat(result.lng)
      const lat = parseFloat(result.lat)
      
      console.log('坐标解析结果 - lng:', lng, 'lat:', lat)
      
      if (isNaN(lng) || isNaN(lat)) {
        console.error('搜索结果坐标无效:', result)
        this.$message.error('搜索结果坐标无效')
        return
      }
      
      // 更新result对象中的坐标
      result.lng = lng
      result.lat = lat
      
      try {
        // 清除之前的搜索标记
        this.clearSearchMarker()
        
        // 定位到搜索结果
        console.log('尝试创建坐标对象，lng:', result.lng, 'lat:', result.lat, '类型:', typeof result.lng, typeof result.lat)
        const lnglat = new this.T.LngLat(result.lng, result.lat)
        console.log('坐标对象创建成功:', lnglat)
        console.log('地图定位到:', result.lng, result.lat)
        
        // 设置地图中心和缩放级别
        console.log('开始设置地图中心和缩放级别')
        this.map.centerAndZoom(lnglat, 15)
        console.log('地图中心和缩放级别设置完成')
        
        // 添加搜索结果标记
        const marker = new this.T.Marker(lnglat)
        
        // 创建信息窗口内容
        const infoContent = `
          <div style="padding: 10px; min-width: 200px; font-family: Arial, sans-serif;">
            <h4 style="margin: 0 0 8px 0; color: #333; font-size: 14px;">${result.name}</h4>
            <p style="margin: 0 0 8px 0; color: #666; font-size: 12px;">${result.address}</p>
            <p style="margin: 0 0 10px 0; color: #999; font-size: 11px;">经度: ${result.lng.toFixed(6)}, 纬度: ${result.lat.toFixed(6)}</p>
            <div style="text-align: center;">
              <button onclick="window.useSearchLocation(${result.lng}, ${result.lat})" 
                      style="background: #409EFF; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                在此位置绘制围栏
              </button>
            </div>
          </div>
        `
        
        // 创建信息窗口
        const infoWindow = new this.T.InfoWindow({
          content: infoContent
        })
        
        // 全局函数，用于信息窗口中的按钮
        const self = this
        window.useSearchLocation = (lng, lat) => {
          console.log('使用搜索位置绘制围栏:', lng, lat)
          
          // 关闭信息窗口
          if (self.searchMarker) {
            self.searchMarker.closeInfoWindow()
          }
          
          // 如果有绘制模式，直接在此位置绘制
          if (self.drawingMode === 'circle') {
            self.drawCircleAtPoint(lng, lat)
          } else if (self.drawingMode === 'rectangle') {
            self.drawRectangleAtPoint(lng, lat)
          } else {
            self.$message.info('请先选择绘制模式（圆形或矩形），然后再使用此位置绘制围栏')
          }
        }
        
        // 点击标记显示信息窗口
        marker.addEventListener('click', () => {
          marker.openInfoWindow(infoWindow)
        })
        
        // 立即显示信息窗口
        marker.openInfoWindow(infoWindow)
        
        // 添加标记到地图
        this.map.addOverLay(marker)
        this.searchMarker = marker
        
        // 清除搜索结果列表
        this.searchResults = []
        
        // 添加到搜索历史
        this.addToSearchHistory(result.name)
        
        this.$message.success(`已定位到：${result.name}`)
        
      } catch (error) {
        console.error('定位搜索结果失败:', error)
        console.error('错误堆栈:', error.stack)
        this.$message.error('定位失败：' + error.message)
        
        // 尝试简单的定位方式
        try {
          console.log('尝试简单定位方式')
          const simpleLngLat = new this.T.LngLat(result.lng, result.lat)
          this.map.centerAndZoom(simpleLngLat, 13)
          this.$message.success('使用简单模式定位成功')
        } catch (simpleError) {
          console.error('简单定位也失败:', simpleError)
        }
      }
    },
    
    // 清除搜索标记
    clearSearchMarker() {
      if (this.searchMarker && this.map) {
        console.log('清除搜索标记')
        this.map.removeOverLay(this.searchMarker)
        this.searchMarker = null
      }
    },
    
    // 地图点击事件
    onMapClick(e) {
      console.log('地图点击事件触发，当前绘制模式:', this.drawingMode)
      
      // 如果不在绘制模式且有选中的围栏，取消选择
      if (!this.drawingMode && this.selectedFenceId) {
        this.selectedFenceId = null
        // 暂时禁用重新渲染，避免性能问题
        // this.renderFenceOnMap()
        console.log('取消围栏选择')
        return
      }
      
      if (!this.drawingMode) {
        console.log('未选择绘制模式')
        return
      }
      
      if (!e || !e.lnglat) {
        console.error('点击事件数据无效:', e)
        return
      }
      
      const lnglat = e.lnglat
      const lng = lnglat.getLng()
      const lat = lnglat.getLat()
      
      console.log('地图点击坐标:', lng, lat)
      
      if (this.drawingMode === 'circle') {
        console.log('开始绘制圆形围栏')
        this.drawCircleAtPoint(lng, lat)
      } else if (this.drawingMode === 'rectangle') {
        console.log('开始绘制矩形围栏')
        this.drawRectangleAtPoint(lng, lat)
      }
    },
    
    // 开始绘制模式
    startDrawing(type) {
      if (!this.mapReady) {
        this.$message.warning('地图尚未准备就绪，请稍后再试')
        return
      }
      
      console.log('开始绘制模式:', type, '地图对象:', this.map, '天地图对象:', this.T)
      
      // 设置绘制模式
      this.drawingMode = type
      
      this.$message.info(this.getDrawingTip())
      console.log('绘制模式设置完成，当前模式:', this.drawingMode)
    },
    
    // 取消绘制模式
    cancelDrawing() {
      console.log('取消绘制模式')
      this.drawingMode = null
    },
    
    // 获取绘制提示信息
    getDrawingTip() {
      switch (this.drawingMode) {
        case 'circle':
          return '请在地图上点击一个位置来绘制圆形围栏（默认半径200米）'
        case 'rectangle':
          return '请在地图上点击一个位置来绘制矩形围栏（默认大小100×100米）'
        default:
          return ''
      }
    },
    
    // 在指定点绘制圆形
    drawCircleAtPoint(lng, lat) {
      try {
        const radius = 200 // 默认半径200米

        console.log('准备绘制圆形围栏，中心点:', lng, lat, '半径:', radius)

        // 创建待命名的围栏数据对象
        const fenceData = {
          id: 'fence_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11),
          name: '', // 暂时为空，等待用户输入
          type: 'circle',
          params: `${lng.toFixed(6)},${lat.toFixed(6)},${radius}`,
          centerLng: lng,
          centerLat: lat,
          radius: radius,
          createTime: new Date().toLocaleString(),
          // 编辑状态初始化
          editingName: false,
          editingParams: false,
          tempName: '',
          tempRadius: 0
        }

        // 保存待命名的围栏数据
        this.pendingFenceData = fenceData

        // 显示名称输入对话框
        this.showFenceNameDialog('circle')

      } catch (error) {
        console.error('准备绘制圆形围栏失败:', error)
        this.$message.error('准备绘制圆形围栏失败')
      }
    },
    
    // 在指定点绘制矩形
    drawRectangleAtPoint(lng, lat) {
      try {
        console.log('开始绘制矩形围栏，参数检查:', { lng, lat, mapReady: this.mapReady, T: !!this.T, map: !!this.map })
        
        if (!this.T || !this.map) {
          console.error('地图或天地图对象不存在')
          this.$message.error('地图未准备就绪，请稍后再试')
          return
        }
        
        const width = 100 // 默认宽度100米
        const height = 100 // 默认高度100米
        
        console.log('绘制矩形围栏，中心点:', lng, lat, '尺寸:', width, 'x', height)
        
        // 创建待命名的围栏数据对象
        const fenceData = {
          id: 'fence_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11),
          name: '', // 暂时为空，等待用户输入
          type: 'rectangle',
          params: `${lng.toFixed(6)},${lat.toFixed(6)},${width},${height}`,
          centerLng: lng,
          centerLat: lat,
          width: width,
          height: height,
          createTime: new Date().toLocaleString(),
          // 编辑状态初始化
          editingName: false,
          editingParams: false,
          tempName: '',
          tempWidth: 0,
          tempHeight: 0
        }

        console.log('设置矩形参数:', fenceData.params)

        // 保存待命名的围栏数据
        this.pendingFenceData = fenceData

        // 显示名称输入对话框
        this.showFenceNameDialog('rectangle')
      } catch (error) {
        console.error('绘制矩形围栏失败:', error)
        this.$message.error('绘制矩形围栏失败: ' + error.message)
      }
    },
    
    // 加载围栏数据
    async loadFenceData() {
      const id = this.$route.params.id
      if (id) {
        try {
          console.log('开始加载围栏数据，ID:', id)
          
          // 从后端API加载围栏数据
          const response = await queryFenceById(id)
          
          if (response.code === 0 && response.data) {
            const fenceData = response.data
            
            // 设置表单数据
            this.form = {
              id: fenceData.id,
              name: fenceData.name || '围栏编辑',
              description: fenceData.description || '',
              fences: this.parseFenceCoordinates(fenceData) // 解析围栏坐标数据
            }
            
            console.log('围栏数据加载成功:', this.form)
            
            // 等待地图准备就绪后渲染围栏
            this.$nextTick(() => {
              if (this.mapReady) {
                this.renderFenceOnMap()
              }
            })
            
          } else {
            console.warn('获取围栏数据响应异常:', response)
            this.loadDefaultFenceData(id)
          }
          
        } catch (error) {
          console.error('加载围栏数据失败:', error)
          this.$message.error('加载围栏数据失败，使用默认数据')
          this.loadDefaultFenceData(id)
        }
      } else {
        // 新建围栏
        this.form = {
          id: null,
          name: '新建围栏',
          description: '请在地图上绘制围栏',
          fences: []
        }
      }
    },

    // 加载默认围栏数据（后备方案）
    loadDefaultFenceData(id) {
      this.form = {
        id: id,
        name: '围栏编辑',
        description: '请在地图上绘制围栏',
        fences: []
      }
      console.log('使用默认围栏数据')
    },

    // 解析围栏坐标数据
    parseFenceCoordinates(fenceData) {
      const fences = []
      
      try {
        // 根据后端数据结构解析围栏坐标
        if (fenceData.type && fenceData.coordinates) {
          const fence = {
            id: fenceData.id || 'fence_' + Date.now(),
            name: fenceData.name || '围栏',
            type: fenceData.type,
            createTime: fenceData.createTime || new Date().toLocaleString(),
            editingName: false,
            editingParams: false,
            tempName: '',
            tempRadius: 0,
            tempWidth: 0,
            tempHeight: 0
          }

          // 解析不同类型的围栏坐标
          if (fenceData.type === 'circle') {
            const coords = fenceData.coordinates.split(',')
            if (coords.length >= 3) {
              fence.centerLng = parseFloat(coords[0])
              fence.centerLat = parseFloat(coords[1])
              fence.radius = parseFloat(coords[2])
              fence.params = fenceData.coordinates
              fences.push(fence)
            }
          } else if (fenceData.type === 'rectangle') {
            const coords = fenceData.coordinates.split(',')
            if (coords.length >= 4) {
              fence.centerLng = parseFloat(coords[0])
              fence.centerLat = parseFloat(coords[1])
              fence.width = parseFloat(coords[2])
              fence.height = parseFloat(coords[3])
              fence.params = fenceData.coordinates
              fences.push(fence)
            }
          } else if (fenceData.type === 'polygon') {
            // 多边形暂时不解析，保留原始数据
            fence.polygon = fenceData.coordinates
            fence.params = fenceData.coordinates
            fences.push(fence)
          }
        }
        
        console.log('解析围栏坐标完成，围栏数量:', fences.length)
      } catch (error) {
        console.error('解析围栏坐标失败:', error)
      }
      
      return fences
    },

    // 加载围栏列表（当没有指定ID时）
    async loadFenceList() {
      this.loadingFenceList = true
      try {
        console.log('开始加载围栏列表')
        
        const response = await queryFences({
          page: 1,
          count: 50, // 加载前50个围栏
          query: '',
          type: '',
          status: 'active'
        })
        
        if (response.code === 0 && response.data) {
          const fenceList = response.data.content || response.data.list || []
          
          console.log('围栏列表加载成功，数量:', fenceList.length)
          
          // 将围栏列表转换为本地格式并添加到地图
          if (fenceList.length > 0) {
            const convertedFences = []
            
            fenceList.forEach(fenceData => {
              const parsedFences = this.parseFenceCoordinates(fenceData)
              convertedFences.push(...parsedFences)
            })
            
            // 更新表单中的围栏数据
            this.form.fences = convertedFences
            this.form.name = '围栏列表管理'
            this.form.description = `当前共有 ${convertedFences.length} 个围栏`
            
            // 渲染到地图上
            this.$nextTick(() => {
              if (this.mapReady) {
                this.renderFenceOnMap()
                // 适应所有围栏
                setTimeout(() => {
                  this.fitAllFences()
                }, 500)
              }
            })
            
            this.$message.success(`已加载 ${convertedFences.length} 个围栏`)
          } else {
            this.$message.info('暂无围栏数据')
          }
          
        } else {
          console.warn('获取围栏列表响应异常:', response)
          this.$message.warning('获取围栏列表失败')
        }
        
      } catch (error) {
        console.error('加载围栏列表失败:', error)
        this.$message.error('加载围栏列表失败，请检查网络连接')
      } finally {
        this.loadingFenceList = false
      }
    },

    // 从服务器重新加载围栏列表
    async loadFenceListFromServer() {
      // 清除当前地图上的围栏
      this.clearAllOverlays()
      this.form.fences = []
      
      // 重新加载
      await this.loadFenceList()
    },
    
    // 在地图上渲染围栏
    renderFenceOnMap() {
      if (!this.T || !this.map || !this.mapReady) {
        console.log('地图未准备就绪，无法渲染围栏')
        return
      }

      console.log('开始渲染围栏，数量:', this.form.fences.length)

      // 设置重新渲染标志
      this.isRerendering = true

      // 只清除覆盖物，不重置绘制模式
      this.clearAllOverlays()

      // 渲染所有围栏
      this.form.fences.forEach(fence => {
        if (fence.type === 'circle') {
          this.renderCircle(fence)
        } else if (fence.type === 'rectangle') {
          this.renderRectangle(fence)
        }
      })

      // 重置重新渲染标志
      this.isRerendering = false

      // 渲染完成后显示所有标签
      this.$nextTick(() => {
        this.showAllFenceLabels()
      })

      console.log(`已渲染${this.form.fences.length}个围栏`)
    },
    
    // 渲染圆形围栏
    renderCircle(fenceData) {
      try {
        console.log('渲染圆形围栏:', fenceData)
        
        const center = new this.T.LngLat(fenceData.centerLng, fenceData.centerLat)
        
        // 根据是否选中设置不同的颜色
        const isSelected = this.selectedFenceId === fenceData.id
        const color = isSelected ? '#FF6B35' : '#409EFF'
        const fillOpacity = isSelected ? 0.4 : 0.3
        
        const circle = new this.T.Circle(center, fenceData.radius, {
        color: color,
          weight: 3,
          opacity: 0.8,
          fillColor: color,
          fillOpacity: fillOpacity
        })
        
        this.addOverlay(circle, fenceData)

        // 添加围栏名称标签
        if (fenceData.name) {
          console.log('准备添加圆形围栏标签:', fenceData.name)
          this.addFenceLabel(fenceData, center)
        }

        // 只在新创建围栏时居中，避免频繁移动地图
        if (!this.isRerendering) {
          this.map.centerAndZoom(center, 15)
        }

        console.log('圆形围栏渲染完成')
      } catch (error) {
        console.error('渲染圆形围栏失败:', error)
        this.$message.error('渲染圆形围栏失败')
      }
    },
    
    // 渲染矩形围栏
    renderRectangle(fenceData) {
      try {
        console.log('渲染矩形围栏:', fenceData)
        
        const centerLng = fenceData.centerLng
        const centerLat = fenceData.centerLat
        const width = fenceData.width
        const height = fenceData.height
        
        console.log('矩形参数:', { centerLng, centerLat, width, height })
        
        // 根据是否选中设置不同的颜色
        const isSelected = this.selectedFenceId === fenceData.id
        const color = isSelected ? '#FF6B35' : '#E6A23C'
        const fillOpacity = isSelected ? 0.4 : 0.3
        
        // 计算矩形四个角的坐标
        const earthRadius = 6378137 // 地球半径（米）
        const latOffset = (height / 2) / earthRadius * (180 / Math.PI)
        const lngOffset = (width / 2) / earthRadius * (180 / Math.PI) / Math.cos(centerLat * Math.PI / 180)
        
        const points = [
          new this.T.LngLat(centerLng - lngOffset, centerLat + latOffset), // 左上
          new this.T.LngLat(centerLng + lngOffset, centerLat + latOffset), // 右上
          new this.T.LngLat(centerLng + lngOffset, centerLat - latOffset), // 右下
          new this.T.LngLat(centerLng - lngOffset, centerLat - latOffset)  // 左下
        ]
        
        console.log('矩形围栏坐标点:', points)
        
        const polygon = new this.T.Polygon(points, {
          color: color,
          weight: 3,
          opacity: 0.8,
          fillColor: color,
          fillOpacity: fillOpacity
        })
        
        this.addOverlay(polygon, fenceData)

        // 添加围栏名称标签
        if (fenceData.name) {
          console.log('准备添加矩形围栏标签:', fenceData.name)
          this.addFenceLabel(fenceData, new this.T.LngLat(centerLng, centerLat))
        }

        // 只在新创建围栏时居中，避免频繁移动地图
        if (!this.isRerendering) {
          this.map.centerAndZoom(new this.T.LngLat(centerLng, centerLat), 15)
        }

        console.log('矩形围栏渲染完成')
      } catch (error) {
        console.error('渲染矩形围栏失败:', error)
        this.$message.error('渲染矩形围栏失败: ' + error.message)
      }
    },
    
    // 清除绘制
    clearDrawing() {
      this.clearAllOverlays()
      this.clearSearchMarker()
      this.drawingMode = null
      this.searchResults = []
      this.selectedFenceId = null // 清除选中状态
    },
    
    // 只清除地图覆盖物（用于清除按钮）
    clearOverlayOnly() {
      this.clearAllOverlays()
      this.clearSearchMarker()
      this.searchResults = []
      
      // 清空表单中的围栏数据
      this.form.fences = []
      this.selectedFenceId = null
      
      this.$message.success('已清除所有围栏')
    },
    
    // 清除所有覆盖物
    clearAllOverlays() {
      if (this.overlays.length > 0 && this.map) {
        console.log('清除所有覆盖物，数量:', this.overlays.length)
        this.overlays.forEach(item => {
          this.map.removeOverLay(item.overlay)
        })
        this.overlays = []
      }

      // 同时清除所有围栏标签
      this.clearAllFenceLabels()
    },
    
    // 添加覆盖物到地图
    addOverlay(overlay, fenceData) {
      if (this.map && overlay) {
        this.map.addOverLay(overlay)
        this.overlays.push({
          overlay: overlay,
          fenceId: fenceData.id,
          type: fenceData.type
        })
        console.log('添加覆盖物到地图，当前覆盖物数量:', this.overlays.length)
      }
    },
    
    // 移除指定的覆盖物
    removeOverlay(fenceId) {
      const index = this.overlays.findIndex(item => item.fenceId === fenceId)
      if (index !== -1) {
        const overlayItem = this.overlays[index]
        this.map.removeOverLay(overlayItem.overlay)
        this.overlays.splice(index, 1)
        console.log('移除覆盖物，ID:', fenceId, '剩余数量:', this.overlays.length)
      }
    },

    // 添加围栏名称标签
    addFenceLabel(fenceData, position) {
      if (!this.T || !this.map || !fenceData.name) {
        console.log('标签创建条件不满足:', {
          T: !!this.T,
          map: !!this.map,
          name: fenceData.name
        })
        return
      }

      try {
        console.log('开始创建围栏标签:', fenceData.name, '位置:', position)

        // 使用安全的标签创建方法
        const label = this.createSafeLabel(fenceData, position)

        if (label) {
          // 添加到地图
          this.map.addOverLay(label)

          // 存储标签引用
          this.fenceLabels.push({
            label: label,
            fenceId: fenceData.id
          })

          console.log('围栏标签已成功添加到地图:', fenceData.name)
        } else {
          console.error('无法创建围栏标签')
        }

      } catch (error) {
        console.error('添加围栏标签失败:', error)
        console.error('错误详情:', error.stack)
      }
    },

    // 切换围栏标签显示/隐藏
    toggleFenceLabels() {
      this.showFenceLabels = !this.showFenceLabels

      if (this.showFenceLabels) {
        // 显示标签：为所有围栏添加标签
        this.form.fences.forEach(fence => {
          let position
          if (fence.type === 'circle') {
            position = new this.T.LngLat(fence.centerLng, fence.centerLat)
          } else if (fence.type === 'rectangle') {
            position = new this.T.LngLat(fence.centerLng, fence.centerLat)
          }
          if (position) {
            this.addFenceLabel(fence, position)
          }
        })
        this.$message.success('围栏标签已显示')
      } else {
        // 隐藏标签：清除所有标签
        this.clearAllFenceLabels()
        this.$message.success('围栏标签已隐藏')
      }
    },

    // 清除所有围栏标签
    clearAllFenceLabels() {
      if (this.fenceLabels.length > 0 && this.map) {
        this.fenceLabels.forEach(item => {
          this.map.removeOverLay(item.label)
        })
        this.fenceLabels = []
        console.log('所有围栏标签已清除')
      }
    },

    // 移除指定围栏的标签
    removeFenceLabel(fenceId) {
      const index = this.fenceLabels.findIndex(item => item.fenceId === fenceId)
      if (index !== -1) {
        const labelItem = this.fenceLabels[index]
        this.map.removeOverLay(labelItem.label)
        this.fenceLabels.splice(index, 1)
        console.log('围栏标签已移除，ID:', fenceId)
      }
    },

    // 开始编辑围栏名称
    startEditName(fence) {
      fence.editingName = true
      fence.tempName = fence.name
      this.$forceUpdate()

      // 聚焦到输入框
      this.$nextTick(() => {
        const inputs = this.$refs.nameInput
        if (inputs) {
          const input = Array.isArray(inputs) ? inputs.find(inp => inp) : inputs
          if (input) {
            input.focus()
            input.select()
          }
        }
      })
    },

    // 保存名称编辑
    saveNameEdit(fence) {
      if (fence.tempName && fence.tempName.trim()) {
        const oldName = fence.name
        fence.name = fence.tempName.trim()
        fence.editingName = false

        // 强制更新视图
        this.$forceUpdate()

        // 更新地图标签
        this.$nextTick(() => {
          this.updateFenceLabel(fence)
        })

        this.$message.success(`围栏名称已更新: ${oldName} → ${fence.name}`)
        console.log('围栏名称已更新:', fence.id, oldName, '→', fence.name)
      } else {
        this.$message.warning('围栏名称不能为空')
        this.cancelNameEdit(fence)
      }
    },

    // 取消名称编辑
    cancelNameEdit(fence) {
      fence.editingName = false
      fence.tempName = fence.name
      this.$forceUpdate()
    },

    // 开始编辑围栏参数
    startEditParams(fence) {
      fence.editingParams = true

      if (fence.type === 'circle') {
        fence.tempRadius = fence.radius
      } else if (fence.type === 'rectangle') {
        fence.tempWidth = fence.width
        fence.tempHeight = fence.height
      }

      this.$forceUpdate()
    },

    // 保存参数编辑
    saveParamsEdit(fence) {
      let updated = false
      let updateInfo = []

      if (fence.type === 'circle') {
        if (fence.tempRadius && fence.tempRadius !== fence.radius) {
          fence.radius = fence.tempRadius
          fence.params = `${fence.centerLng.toFixed(6)},${fence.centerLat.toFixed(6)},${fence.radius}`
          updateInfo.push(`半径: ${fence.radius}米`)
          updated = true
        }
      } else if (fence.type === 'rectangle') {
        if (fence.tempWidth && fence.tempWidth !== fence.width) {
          fence.width = fence.tempWidth
          updateInfo.push(`宽度: ${fence.width}米`)
          updated = true
        }
        if (fence.tempHeight && fence.tempHeight !== fence.height) {
          fence.height = fence.tempHeight
          updateInfo.push(`高度: ${fence.height}米`)
          updated = true
        }
        if (updated) {
          fence.params = `${fence.centerLng.toFixed(6)},${fence.centerLat.toFixed(6)},${fence.width},${fence.height}`
        }
      }

      fence.editingParams = false

      if (updated) {
        // 更新地图上的围栏
        this.updateFenceOnMap(fence)
        this.$message.success(`围栏参数已更新: ${updateInfo.join(', ')}`)
        console.log('围栏参数已更新:', fence.id, updateInfo)
      }

      this.$forceUpdate()
    },

    // 取消参数编辑
    cancelParamsEdit(fence) {
      fence.editingParams = false

      // 恢复原始值
      if (fence.type === 'circle') {
        fence.tempRadius = fence.radius
      } else if (fence.type === 'rectangle') {
        fence.tempWidth = fence.width
        fence.tempHeight = fence.height
      }

      this.$forceUpdate()
    },

    // 更新围栏标签
    updateFenceLabel(fence) {
      if (!this.showFenceLabels || !fence.name) return

      // 先移除旧标签
      this.removeFenceLabel(fence.id)

      // 添加新标签
      let position
      if (fence.type === 'circle') {
        position = new this.T.LngLat(fence.centerLng, fence.centerLat)
      } else if (fence.type === 'rectangle') {
        position = new this.T.LngLat(fence.centerLng, fence.centerLat)
      }

      if (position) {
        this.addFenceLabel(fence, position)
      }
    },

    // 更新地图上的围栏
    updateFenceOnMap(fence) {
      try {
        // 先移除旧的围栏覆盖物
        this.removeOverlay(fence.id)

        // 重新渲染围栏
        if (fence.type === 'circle') {
          this.renderCircleFromData(fence)
        } else if (fence.type === 'rectangle') {
          this.renderRectangleFromData(fence)
        }

        console.log('围栏已在地图上更新:', fence.id)
      } catch (error) {
        console.error('更新地图围栏失败:', error)
        this.$message.error('更新地图围栏失败')
      }
    },

    // 从数据渲染圆形围栏
    renderCircleFromData(fenceData) {
      if (!this.T || !this.map) return

      const center = new this.T.LngLat(fenceData.centerLng, fenceData.centerLat)
      const circle = new this.T.Circle(center, fenceData.radius, {
        color: '#409EFF',
        weight: 2,
        opacity: 0.8,
        fillColor: '#409EFF',
        fillOpacity: 0.2
      })

      this.addOverlay(circle, fenceData)

      // 添加标签
      if (this.showFenceLabels && fenceData.name) {
        this.addFenceLabel(fenceData, center)
      }
    },

    // 从数据渲染矩形围栏
    renderRectangleFromData(fenceData) {
      if (!this.T || !this.map) return

      const centerLng = fenceData.centerLng
      const centerLat = fenceData.centerLat
      const width = fenceData.width
      const height = fenceData.height

      // 计算矩形的四个角点
      const halfWidth = width / 2 / 111000 // 转换为度
      const halfHeight = height / 2 / 111000

      const points = [
        new this.T.LngLat(centerLng - halfWidth, centerLat + halfHeight),
        new this.T.LngLat(centerLng + halfWidth, centerLat + halfHeight),
        new this.T.LngLat(centerLng + halfWidth, centerLat - halfHeight),
        new this.T.LngLat(centerLng - halfWidth, centerLat - halfHeight)
      ]

      const polygon = new this.T.Polygon(points, {
        color: '#E6A23C',
        weight: 2,
        opacity: 0.8,
        fillColor: '#E6A23C',
        fillOpacity: 0.2
      })

      this.addOverlay(polygon, fenceData)

      // 添加标签
      if (this.showFenceLabels && fenceData.name) {
        this.addFenceLabel(fenceData, new this.T.LngLat(centerLng, centerLat))
      }
    },

    // 强制显示所有围栏标签
    showAllFenceLabels() {
      if (!this.mapReady || this.form.fences.length === 0) return

      console.log('开始显示所有围栏标签，围栏数量:', this.form.fences.length)

      // 清除现有标签
      this.clearAllFenceLabels()

      // 为每个围栏添加标签
      this.form.fences.forEach(fence => {
        if (fence.name) {
          let position
          if (fence.type === 'circle') {
            position = new this.T.LngLat(fence.centerLng, fence.centerLat)
          } else if (fence.type === 'rectangle') {
            position = new this.T.LngLat(fence.centerLng, fence.centerLat)
          }

          if (position) {
            this.addFenceLabel(fence, position)
            console.log('已添加围栏标签:', fence.name, '位置:', fence.centerLng, fence.centerLat)
          }
        }
      })

      // 确保标签显示状态为true
      this.showFenceLabels = true

      console.log('所有围栏标签显示完成，标签数量:', this.fenceLabels.length)
    },

    // 安全的标签创建方法（参考截图代码）
    createSafeLabel(fenceData, position) {
      if (!this.T || !this.map || !fenceData.name) {
        return null
      }

      try {
        // 参考截图代码，使用T.Label创建文字标注
        const label = new this.T.Label({
          text: fenceData.name,
          position: position,
          offset: new this.T.Point(-0, 0) // 参考截图的offset设置
        })

        // 添加到地图
        this.map.addOverLay(label)

        console.log('围栏标签创建成功:', fenceData.name)
        return label

      } catch (error) {
        console.error('创建标签失败:', error)
        return null
      }
    },

    // 简化的标签创建方法
    createSimpleLabel(fenceData, position) {
      if (!this.T || !this.map || !fenceData.name) return null

      try {
        // 使用最简单的方式创建标签 - 使用Marker
        const labelText = fenceData.name

        // 创建自定义HTML内容
        const labelHtml = `
          <div style="
            background: #409EFF;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            border: 2px solid white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.3);
            white-space: nowrap;
            text-align: center;
            min-width: 60px;
          ">${labelText}</div>
        `

        // 使用InfoWindow作为标签
        const label = new this.T.InfoWindow({
          content: labelHtml,
          position: position,
          offset: new this.T.Point(0, -25),
          autoPan: false,
          closeWhenClickMap: false,
          isCustom: false
        })

        return label
      } catch (error) {
        console.error('创建简化标签失败:', error)
        return null
      }
    },

    // 调试标签状态
    debugLabels() {
      console.log('=== 标签调试信息 ===')
      console.log('地图状态:', {
        mapReady: this.mapReady,
        map: !!this.map,
        T: !!this.T
      })
      console.log('标签状态:', {
        showFenceLabels: this.showFenceLabels,
        fenceLabelsCount: this.fenceLabels.length,
        fenceLabels: this.fenceLabels
      })
      console.log('围栏数据:', {
        fencesCount: this.form.fences.length,
        fences: this.form.fences.map(f => ({
          id: f.id,
          name: f.name,
          type: f.type,
          centerLng: f.centerLng,
          centerLat: f.centerLat
        }))
      })

      // 检查天地图API
      if (this.T) {
        console.log('天地图API可用:', {
          Label: !!this.T.Label,
          Marker: !!this.T.Marker,
          InfoWindow: !!this.T.InfoWindow,
          Point: !!this.T.Point,
          LngLat: !!this.T.LngLat
        })
      }

      // 尝试手动创建一个测试标签
      if (this.map && this.T && this.form.fences.length > 0) {
        const testFence = this.form.fences[0]
        console.log('尝试为第一个围栏创建测试标签:', testFence.name)

        try {
          const testPosition = new this.T.LngLat(testFence.centerLng, testFence.centerLat)
          this.addFenceLabel(testFence, testPosition)
        } catch (error) {
          console.error('测试标签创建失败:', error)
        }
      }

      this.$message.info('标签调试信息已输出到控制台，请按F12查看')
    },

    // 显示围栏名称输入对话框
    showFenceNameDialog(fenceType) {
      // 重置表单
      this.fenceNameForm.name = ''

      // 生成默认名称建议
      const defaultName = fenceType === 'circle'
        ? `圆形围栏${this.form.fences.length + 1}`
        : `矩形围栏${this.form.fences.length + 1}`

      // 设置占位符
      this.$nextTick(() => {
        if (this.$refs.fenceNameInput) {
          this.$refs.fenceNameInput.$el.querySelector('input').placeholder = `建议：${defaultName}`
        }
      })

      // 显示对话框
      this.fenceNameDialog = true

      // 聚焦到输入框
      this.$nextTick(() => {
        if (this.$refs.fenceNameInput) {
          this.$refs.fenceNameInput.focus()
        }
      })
    },

    // 确认围栏名称
    confirmFenceName() {
      if (!this.pendingFenceData) {
        this.$message.error('没有待命名的围栏数据')
        return
      }

      // 如果用户输入了名称，使用用户输入的名称
      if (this.fenceNameForm.name && this.fenceNameForm.name.trim()) {
        this.pendingFenceData.name = this.fenceNameForm.name.trim()
      } else {
        // 如果没有输入名称，自动生成
        const autoName = this.pendingFenceData.type === 'circle'
          ? `圆形围栏${this.form.fences.length + 1}`
          : `矩形围栏${this.form.fences.length + 1}`
        this.pendingFenceData.name = autoName
      }

      // 完成围栏创建
      this.completeFenceCreation()
    },

    // 跳过围栏命名
    skipFenceNaming() {
      if (!this.pendingFenceData) {
        this.$message.error('没有待命名的围栏数据')
        return
      }

      // 自动生成名称
      const autoName = this.pendingFenceData.type === 'circle'
        ? `圆形围栏${this.form.fences.length + 1}`
        : `矩形围栏${this.form.fences.length + 1}`
      this.pendingFenceData.name = autoName

      // 完成围栏创建
      this.completeFenceCreation()
    },

    // 取消围栏命名
    cancelFenceNaming() {
      this.fenceNameDialog = false
      this.pendingFenceData = null
      this.drawingMode = null
      this.$message.info('已取消围栏绘制')
    },

    // 完成围栏创建
    completeFenceCreation() {
      if (!this.pendingFenceData) return

      try {
        // 添加到围栏数组
        this.form.fences.push(this.pendingFenceData)

        // 渲染围栏
        if (this.pendingFenceData.type === 'circle') {
          this.renderCircle(this.pendingFenceData)
        } else if (this.pendingFenceData.type === 'rectangle') {
          this.renderRectangle(this.pendingFenceData)
        }

        // 关闭对话框
        this.fenceNameDialog = false

        // 重置绘制模式
        this.drawingMode = null

        // 显示成功消息
        const typeName = this.pendingFenceData.type === 'circle' ? '圆形' : '矩形'
        this.$message.success(`${typeName}围栏"${this.pendingFenceData.name}"创建成功，当前共${this.form.fences.length}个围栏`)

        // 清除待命名数据
        this.pendingFenceData = null

      } catch (error) {
        console.error('完成围栏创建失败:', error)
        this.$message.error('围栏创建失败: ' + error.message)
      }
    },

    // 测试围栏创建
    testFenceCreation() {
      if (!this.mapReady) {
        this.$message.error('地图未准备就绪')
        return
      }

      try {
        // 获取地图中心位置
        const center = this.map.getCenter()
        const lng = center.getLng()
        const lat = center.getLat()

        // 创建测试圆形围栏
        const testFence = {
          id: 'test_fence_' + Date.now(),
          name: `测试围栏${this.form.fences.length + 1}`,
          type: 'circle',
          centerLng: lng,
          centerLat: lat,
          radius: 200,
          params: `${lng.toFixed(6)},${lat.toFixed(6)},200`,
          createTime: new Date().toLocaleString(),
          editingName: false,
          editingParams: false,
          tempName: '',
          tempRadius: 0
        }

        // 添加到围栏数组
        this.form.fences.push(testFence)

        // 渲染围栏
        this.renderCircle(testFence)

        this.$message.success(`测试围栏创建成功，位置: ${lng.toFixed(4)}, ${lat.toFixed(4)}`)
        console.log('测试围栏创建成功:', testFence)

      } catch (error) {
        console.error('测试围栏创建失败:', error)
        this.$message.error('测试围栏创建失败: ' + error.message)
      }
    },

    // 显示精确绘制对话框
    showPreciseDrawDialog() {
      // 重置表单
      this.preciseForm = {
        type: 'circle',
        name: `精确围栏${this.form.fences.length + 1}`,
        centerLng: 116.397428,
        centerLat: 39.90923,
        radius: 200,
        width: 100,
        height: 100
      }

      // 如果地图已加载，使用当前地图中心作为默认位置
      if (this.map && this.mapReady) {
        try {
          const center = this.map.getCenter()
          this.preciseForm.centerLng = center.getLng()
          this.preciseForm.centerLat = center.getLat()
        } catch (error) {
          console.error('获取地图中心失败:', error)
        }
      }

      this.preciseDrawDialog = true
    },

    // 预览精确围栏
    previewPreciseFence() {
      this.$refs.preciseForm.validate((valid) => {
        if (valid) {
          try {
            // 定位到指定位置
            const center = new this.T.LngLat(this.preciseForm.centerLng, this.preciseForm.centerLat)
            this.map.centerAndZoom(center, 15)

            // 清除之前的预览
            this.clearPreview()

            // 创建预览围栏
            let previewOverlay
            if (this.preciseForm.type === 'circle') {
              previewOverlay = new this.T.Circle(center, this.preciseForm.radius, {
                color: '#F56C6C',
                weight: 2,
                opacity: 0.8,
                fillColor: '#F56C6C',
                fillOpacity: 0.3
              })
            } else if (this.preciseForm.type === 'rectangle') {
              const centerLng = this.preciseForm.centerLng
              const centerLat = this.preciseForm.centerLat
              const width = this.preciseForm.width
              const height = this.preciseForm.height

              // 计算矩形的四个角点
              const earthRadius = 6378137
              const latOffset = (height / 2) / earthRadius * (180 / Math.PI)
              const lngOffset = (width / 2) / earthRadius * (180 / Math.PI) / Math.cos(centerLat * Math.PI / 180)

              const points = [
                new this.T.LngLat(centerLng - lngOffset, centerLat + latOffset),
                new this.T.LngLat(centerLng + lngOffset, centerLat + latOffset),
                new this.T.LngLat(centerLng + lngOffset, centerLat - latOffset),
                new this.T.LngLat(centerLng - lngOffset, centerLat - latOffset)
              ]

              previewOverlay = new this.T.Polygon(points, {
                color: '#F56C6C',
                weight: 2,
                opacity: 0.8,
                fillColor: '#F56C6C',
                fillOpacity: 0.3
              })
            }

            if (previewOverlay) {
              this.map.addOverLay(previewOverlay)
              this.previewOverlay = previewOverlay

              // 添加预览标签
              const previewLabel = new this.T.Label({
                text: this.preciseForm.name + ' (预览)',
                position: center,
                offset: new this.T.Point(0, -10)
              })

              previewLabel.setLabelStyle({
                color: '#F56C6C',
                fontSize: '12px',
                fontWeight: 'bold',
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                border: '1px solid #F56C6C',
                borderRadius: '4px',
                padding: '4px 8px'
              })

              this.map.addOverLay(previewLabel)
              this.previewLabel = previewLabel
            }

            this.$message.success('预览已生成，请检查位置和大小是否正确')
          } catch (error) {
            console.error('预览围栏失败:', error)
            this.$message.error('预览围栏失败: ' + error.message)
          }
        }
      })
    },

    // 清除预览
    clearPreview() {
      if (this.previewOverlay) {
        this.map.removeOverLay(this.previewOverlay)
        this.previewOverlay = null
      }
      if (this.previewLabel) {
        this.map.removeOverLay(this.previewLabel)
        this.previewLabel = null
      }
    },

    // 获取当前位置
    getCurrentLocation() {
      if (navigator.geolocation) {
        this.$message.info('正在获取当前位置...')
        navigator.geolocation.getCurrentPosition(
          (position) => {
            this.preciseForm.centerLng = position.coords.longitude
            this.preciseForm.centerLat = position.coords.latitude
            this.$message.success('当前位置获取成功')
          },
          (error) => {
            console.error('获取位置失败:', error)
            this.$message.error('获取位置失败，请手动输入坐标')
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 60000
          }
        )
      } else {
        this.$message.error('浏览器不支持地理定位')
      }
    },

    // 创建精确围栏
    createPreciseFence() {
      this.$refs.preciseForm.validate((valid) => {
        if (valid) {
          this.creatingPreciseFence = true

          try {
            // 创建围栏数据
            const fenceData = {
              id: 'fence_' + Date.now() + '_' + Math.random().toString(36).substring(2, 11),
              name: this.preciseForm.name,
              type: this.preciseForm.type,
              centerLng: this.preciseForm.centerLng,
              centerLat: this.preciseForm.centerLat,
              createTime: new Date().toLocaleString(),
              // 编辑状态初始化
              editingName: false,
              editingParams: false,
              tempName: '',
              tempRadius: 0,
              tempWidth: 0,
              tempHeight: 0
            }

            if (this.preciseForm.type === 'circle') {
              fenceData.radius = this.preciseForm.radius
              fenceData.params = `${this.preciseForm.centerLng.toFixed(6)},${this.preciseForm.centerLat.toFixed(6)},${this.preciseForm.radius}`
            } else if (this.preciseForm.type === 'rectangle') {
              fenceData.width = this.preciseForm.width
              fenceData.height = this.preciseForm.height
              fenceData.params = `${this.preciseForm.centerLng.toFixed(6)},${this.preciseForm.centerLat.toFixed(6)},${this.preciseForm.width},${this.preciseForm.height}`
            }

            // 添加到围栏数组
            this.form.fences.push(fenceData)

            // 清除预览
            this.clearPreview()

            // 渲染围栏
            if (fenceData.type === 'circle') {
              this.renderCircle(fenceData)
            } else if (fenceData.type === 'rectangle') {
              this.renderRectangle(fenceData)
            }

            // 关闭对话框
            this.preciseDrawDialog = false
            this.creatingPreciseFence = false

            this.$message.success(`精确围栏创建成功，当前共${this.form.fences.length}个围栏`)

          } catch (error) {
            console.error('创建精确围栏失败:', error)
            this.$message.error('创建精确围栏失败: ' + error.message)
            this.creatingPreciseFence = false
          }
        } else {
          this.creatingPreciseFence = false
        }
      })
    },

    // 地图缩放控制
    zoomIn() {
      if (this.map && this.mapReady) {
        this.map.zoomIn()
      }
    },

    zoomOut() {
      if (this.map && this.mapReady) {
        this.map.zoomOut()
      }
    },

    // 适应所有围栏
    fitAllFences() {
      if (!this.map || !this.mapReady || this.form.fences.length === 0) return

      try {
        // 计算所有围栏的边界
        let minLng = Infinity, maxLng = -Infinity
        let minLat = Infinity, maxLat = -Infinity

        this.form.fences.forEach(fence => {
          if (fence.type === 'circle') {
            const radius = fence.radius
            const earthRadius = 6378137
            const latOffset = radius / earthRadius * (180 / Math.PI)
            const lngOffset = radius / earthRadius * (180 / Math.PI) / Math.cos(fence.centerLat * Math.PI / 180)

            minLng = Math.min(minLng, fence.centerLng - lngOffset)
            maxLng = Math.max(maxLng, fence.centerLng + lngOffset)
            minLat = Math.min(minLat, fence.centerLat - latOffset)
            maxLat = Math.max(maxLat, fence.centerLat + latOffset)
          } else if (fence.type === 'rectangle') {
            const width = fence.width
            const height = fence.height
            const earthRadius = 6378137
            const latOffset = (height / 2) / earthRadius * (180 / Math.PI)
            const lngOffset = (width / 2) / earthRadius * (180 / Math.PI) / Math.cos(fence.centerLat * Math.PI / 180)

            minLng = Math.min(minLng, fence.centerLng - lngOffset)
            maxLng = Math.max(maxLng, fence.centerLng + lngOffset)
            minLat = Math.min(minLat, fence.centerLat - latOffset)
            maxLat = Math.max(maxLat, fence.centerLat + latOffset)
          }
        })

        // 创建边界
        const bounds = new this.T.LngLatBounds(
          new this.T.LngLat(minLng, minLat),
          new this.T.LngLat(maxLng, maxLat)
        )

        // 适应边界
        this.map.fitBounds(bounds)

        this.$message.success('已适应所有围栏范围')
      } catch (error) {
        console.error('适应围栏范围失败:', error)
        this.$message.error('适应围栏范围失败')
      }
    },

    // 重置地图视图
    resetMapView() {
      if (this.map && this.mapReady) {
        const initialCenter = new this.T.LngLat(116.397428, 39.90923)
        this.map.centerAndZoom(initialCenter, 12)
        this.$message.success('已重置到初始位置')
      }
    },

    // 切换测量模式
    toggleMeasure() {
      this.measureMode = !this.measureMode
      if (this.measureMode) {
        this.$message.info('测量模式已开启，点击地图开始测量距离')
      } else {
        this.$message.info('测量模式已关闭')
      }
    },

    // 清除测量
    clearMeasure() {
      if (this.measureOverlays.length > 0) {
        this.measureOverlays.forEach(overlay => {
          this.map.removeOverLay(overlay)
        })
        this.measureOverlays = []
        this.$message.success('测量结果已清除')
      }
    },

    // 提交表单
    async submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 检查是否至少有一个围栏
          if (this.form.fences.length === 0) {
            this.$message.error('请先在地图上绘制至少一个围栏')
            return
          }
          
          this.submitting = true
          
          try {
            console.log('开始提交围栏数据:', this.form)
            
            // 准备提交的围栏数据
            const fenceDataToSubmit = this.prepareFenceDataForSubmit()
            
            let response
            if (this.form.id) {
              // 更新现有围栏
              response = await updateFence(this.form.id, fenceDataToSubmit)
            } else {
              // 创建新围栏
              response = await createFence(fenceDataToSubmit)
            }
            
            if (response.code === 0) {
              const action = this.form.id ? '更新' : '创建'
              this.$message.success(`围栏${action}成功，共提交${this.form.fences.length}个围栏`)
              this.goBack()
            } else {
              this.$message.error(response.msg || '提交失败')
            }
            
          } catch (error) {
            console.error('提交围栏数据失败:', error)
            this.$message.error('提交失败，请重试')
          } finally {
            this.submitting = false
          }
          
        } else {
          this.$message.error('请检查表单输入')
        }
      })
    },

    // 准备提交的围栏数据
    prepareFenceDataForSubmit() {
      const submitData = {
        name: this.form.name,
        description: this.form.description,
        type: this.form.fences.length > 0 ? this.form.fences[0].type : 'circle',
        coordinates: '',
        status: 'active'
      }

      // 处理多个围栏的情况，这里简化为只提交第一个围栏
      // 如果需要支持多个围栏，可能需要修改后端API
      if (this.form.fences.length > 0) {
        const fence = this.form.fences[0]
        
        if (fence.type === 'circle') {
          submitData.coordinates = `${fence.centerLng.toFixed(6)},${fence.centerLat.toFixed(6)},${fence.radius}`
        } else if (fence.type === 'rectangle') {
          submitData.coordinates = `${fence.centerLng.toFixed(6)},${fence.centerLat.toFixed(6)},${fence.width},${fence.height}`
        } else if (fence.type === 'polygon' && fence.polygon) {
          submitData.coordinates = fence.polygon
        }
        
        submitData.type = fence.type
      }

      console.log('准备提交的数据:', submitData)
      return submitData
    },
    
    // 返回
    goBack() {
      this.$router.go(-1)
    },
    
    // 格式化围栏参数显示
    formatFenceParams(fence) {
      if (fence.type === 'circle') {
        return `中心:(${fence.centerLng.toFixed(4)}, ${fence.centerLat.toFixed(4)}) 半径:${fence.radius}m`
      } else if (fence.type === 'rectangle') {
        return `中心:(${fence.centerLng.toFixed(4)}, ${fence.centerLat.toFixed(4)}) 尺寸:${fence.width}×${fence.height}m`
      }
      return fence.params
    },
    
    // 选择围栏
    selectFence(fenceId) {
      this.selectedFenceId = fenceId
      console.log('选择围栏:', fenceId)
      
      // 重新渲染所有围栏以更新颜色
      this.renderFenceOnMap()
    },
    
    // 定位到围栏
    focusFence(fence) {
      if (!this.map || !this.T) return
      
      // 选中当前围栏
      this.selectedFenceId = fence.id
      
      const center = new this.T.LngLat(fence.centerLng, fence.centerLat)
      this.map.centerAndZoom(center, 15)
      
      // 重新渲染所有围栏以更新颜色
      this.renderFenceOnMap()
      
      this.$message.success(`已定位到${fence.type === 'circle' ? '圆形' : '矩形'}围栏`)
    },
    
    // 删除围栏
    deleteFence(index) {
      const fence = this.form.fences[index]
      if (!fence) return
      
      this.$confirm(`确定要删除这个${fence.type === 'circle' ? '圆形' : '矩形'}围栏吗？`, '确认删除', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 如果围栏有ID且不是临时创建的，则调用后端API删除
          if (fence.id && !fence.id.startsWith('fence_')) {
            console.log('删除后端围栏，ID:', fence.id)
            const response = await deleteFence(fence.id)
            
            if (response.code !== 0) {
              this.$message.error(response.msg || '删除失败')
              return
            }
          }
          
          // 从地图移除对应的覆盖物
          this.removeOverlay(fence.id)

          // 移除对应的标签
          this.removeFenceLabel(fence.id)

          // 从数组中移除
          this.form.fences.splice(index, 1)

          // 如果删除的是当前选中的围栏，清除选中状态
          if (this.selectedFenceId === fence.id) {
            this.selectedFenceId = null
          }

          this.$message.success('围栏删除成功')
          
        } catch (error) {
          console.error('删除围栏失败:', error)
          this.$message.error('删除围栏失败，请重试')
        }
      }).catch(() => {
        console.log('取消删除')
      })
    },

    // 快速搜索
    quickSearch(cityName) {
      this.searchKeyword = cityName
      this.searchLocation()
    },
    
    // 测试地图定位功能
    testMapLocation() {
      console.log('测试地图定位功能')
      console.log('地图状态:', { mapReady: this.mapReady, map: !!this.map, T: !!this.T })
      
      if (!this.mapReady || !this.map || !this.T) {
        console.error('地图未准备就绪')
        return
      }
      
      try {
        // 测试定位到天安门
        const testLng = 116.3972
        const testLat = 39.9097
        console.log('测试坐标:', testLng, testLat)
        
        const lnglat = new this.T.LngLat(testLng, testLat)
        console.log('测试坐标对象:', lnglat)
        
        this.map.centerAndZoom(lnglat, 15)
        console.log('测试定位完成')
        
        // 添加测试标记
        const marker = new this.T.Marker(lnglat)
        this.map.addOverLay(marker)
        
        this.$message.success('测试定位成功：天安门')
      } catch (error) {
        console.error('测试定位失败:', error)
        this.$message.error('测试定位失败：' + error.message)
      }
    },

    // 实时搜索输入
    onSearchInput() {
      if (this.searchKeyword.length >= 2) { // 至少两个字符才触发搜索
        this.searchLocation()
      } else {
        this.searchResults = []
        this.searchSuggestions = []
        this.showSuggestions = false
        this.showSearchHistory = false
      }
    },

    // 搜索建议
    async fetchSuggestions() {
      if (!this.searchKeyword.trim()) {
        this.searchSuggestions = []
        this.showSuggestions = false
        return
      }

      try {
        const tk = 'b5ce37dbd64b3f4a990cb9e90fc0aa1e'
        const keyword = encodeURIComponent(this.searchKeyword)
        const suggestUrl = `https://api.tianditu.gov.cn/geocoder?ds={"keyWord":"${keyword}"}&tk=${tk}`

        const script = document.createElement('script')
        const callbackName = 'suggestCallback_' + Date.now()

        window[callbackName] = (data) => {
          if (data.status === '0' && data.result && data.result.length > 0) {
            this.searchSuggestions = data.result.map(item => ({
              name: item.name,
              address: item.formatted_address || item.address || '',
              lng: parseFloat(item.location.lon),
              lat: parseFloat(item.location.lat),
              level: item.level || '',
              tags: item.tags || []
            }))
            this.showSuggestions = true
            this.showSearchHistory = false
            console.log('搜索建议:', this.searchSuggestions)
          } else {
            this.searchSuggestions = []
            this.showSuggestions = false
            this.showSearchHistory = false
            console.log('无搜索建议')
          }
          document.head.removeChild(script)
          delete window[callbackName]
        }

        script.src = suggestUrl + `&callback=${callbackName}`
        script.onerror = () => {
          console.error('搜索建议API调用失败')
          this.searchSuggestions = []
          this.showSuggestions = false
          this.showSearchHistory = false
          document.head.removeChild(script)
          delete window[callbackName]
        }
        document.head.appendChild(script)

        setTimeout(() => {
          if (this.isSearching) { // 如果还在搜索中，则不显示建议
            if (document.head.contains(script)) {
              document.head.removeChild(script)
            }
            if (window[callbackName]) {
              delete window[callbackName]
            }
          }
        }, 5000)

      } catch (error) {
        console.error('搜索建议失败:', error)
        this.searchSuggestions = []
        this.showSuggestions = false
        this.showSearchHistory = false
      }
    },



    // 关闭搜索建议
    closeSuggestions() {
      this.showSuggestions = false
      this.searchSuggestions = []
    },

    // 高亮搜索关键词
    highlightMatch(text, keyword) {
      if (!keyword) return text
      const regex = new RegExp(`(${keyword})`, 'gi')
      return text.replace(regex, '<span style="color: #409EFF; font-weight: bold;">$1</span>')
    },

    // 添加搜索历史
    addSearchHistory(keyword) {
      if (keyword.length < 2) return // 避免添加太短的搜索词
      const history = JSON.parse(localStorage.getItem('searchHistory') || '[]')
      if (!history.includes(keyword)) {
        history.unshift(keyword)
        localStorage.setItem('searchHistory', JSON.stringify(history.slice(0, 10))) // 只保留前10条
      }
    },

    // 显示搜索历史
    showSearchHistory() {
      this.showSearchHistory = true
      this.showSuggestions = false
      this.searchSuggestions = []
    },

    // 清除搜索历史
    clearSearchHistory() {
      this.$confirm('确定要清除所有搜索历史吗？', '确认清除', {
        confirmButtonText: '清除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('searchHistory')
        this.searchHistory = []
        this.$message.success('搜索历史已清除')
      }).catch(() => {
        console.log('取消清除')
      })
    },

    // 选择搜索历史项
    selectHistoryItem(keyword) {
      this.searchKeyword = keyword
      this.searchLocation()
      this.showSearchHistory = false
      this.showSuggestions = false
    },

    // 移除搜索历史项
    removeHistoryItem(index) {
      const history = JSON.parse(localStorage.getItem('searchHistory') || '[]')
      history.splice(index, 1)
      localStorage.setItem('searchHistory', JSON.stringify(history))
      this.searchHistory = history
      this.$message.success('搜索历史已移除')
    },

    // 表格相关方法
    // 获取表格行的类名
    getRowClassName({ row, rowIndex }) {
      if (this.selectedFenceId === row.id) {
        return 'selected-row'
      }
      return ''
    },

    // 表格行点击事件
    onRowClick(row, column, event) {
      this.selectFence(row.id)
    },

    // 获取围栏类型文本
    getFenceTypeText(type) {
      const typeMap = {
        'circle': '圆形',
        'rectangle': '矩形',
        'polygon': '多边形'
      }
      return typeMap[type] || '未知'
    },

    // 获取围栏大小文本
    getFenceSizeText(fence) {
      if (fence.type === 'circle') {
        return `半径: ${fence.radius}米`
      } else if (fence.type === 'rectangle') {
        return `${fence.width}×${fence.height}米`
      } else if (fence.type === 'polygon') {
        return '多边形'
      }
      return '未知'
    },

    // 获取选中围栏的名称
    getSelectedFenceName() {
      if (!this.selectedFenceId) return ''
      const fence = this.form.fences.find(f => f.id === this.selectedFenceId)
      return fence ? fence.name : ''
    },

    onFenceSelectionChange(selected) {
      // 选中的围栏数组
      console.log('选中的围栏:', selected)
      // 可根据业务需要处理选中数据
    },

    // 表格水平拖拽方法
    startTableDrag(e) {
      // 只在表格容器上开始拖拽，不在表格内容上
      if (e.target === this.$refs.fenceTableContainer) {
        this.tableDragging = true
        this.dragStartX = e.clientX
        this.dragStartScrollLeft = this.$refs.fenceTableContainer.scrollLeft
        
        // 改变鼠标样式
        this.$refs.fenceTableContainer.style.cursor = 'grabbing'
        
        // 防止文本选择
        e.preventDefault()
        
        console.log('开始拖拽围栏表格')
      }
    },

    onTableDrag(e) {
      if (!this.tableDragging) return
      
      e.preventDefault()
      
      const deltaX = e.clientX - this.dragStartX
      const newScrollLeft = this.dragStartScrollLeft - deltaX
      
      // 设置滚动位置
      this.$refs.fenceTableContainer.scrollLeft = newScrollLeft
    },

    stopTableDrag() {
      if (this.tableDragging) {
        this.tableDragging = false
        
        // 恢复鼠标样式
        if (this.$refs.fenceTableContainer) {
          this.$refs.fenceTableContainer.style.cursor = 'grab'
        }
        
        console.log('停止拖拽围栏表格')
      }
    },

  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-container {
  position: relative;
  margin-bottom: 10px;
}

.search-input {
  width: 100%;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 300px;
  overflow-y: auto;
}

.search-result-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.search-result-item:hover {
  background-color: #f5f7fa;
}

.search-result-item:last-child {
  border-bottom: none;
}

.result-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.quick-cities {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.quick-label {
  font-size: 14px;
  color: #606266;
  font-weight: bold;
}

.search-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 999;
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: bold;
  color: #303133;
}

.suggestion-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.suggestion-address {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.suggestion-tags {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background-color: #e9ecef;
  color: #495060;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.search-history {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: bold;
  color: #303133;
}

.history-items {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.history-tag {
  cursor: pointer;
}

.map-toolbar {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.debug-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: auto;
  font-size: 12px;
}

.debug-label {
  font-weight: bold;
  color: #606266;
}

.debug-value {
  color: #909399;
  background: white;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #dcdfe6;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

#map {
  border: 1px solid #ddd;
  border-radius: 4px;
}

.no-fences {
  padding: 10px 0;
}

.fence-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.fence-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.fence-item:hover {
  background-color: #f5f7fa;
}

.fence-item:last-child {
  border-bottom: none;
}

.fence-item.selected {
  background-color: #fff2e8;
  border: 2px solid #FF6B35;
  border-radius: 4px;
}

.fence-item.selected .fence-type {
  color: #FF6B35;
  font-weight: 600;
}

.fence-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.fence-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.fence-name-container {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
}

.fence-name {
  font-weight: 600;
  color: #409EFF;
  font-size: 14px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.fence-name:hover {
  background-color: #f0f9ff;
}

.fence-name-edit {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;
}

.fence-name-input {
  flex: 1;
  max-width: 150px;
}

.name-edit-actions {
  display: flex;
  gap: 2px;
}

.name-edit-actions .el-button {
  padding: 4px 6px !important;
  min-width: 24px;
}

.edit-name-btn {
  padding: 2px 4px !important;
  font-size: 12px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.edit-name-btn:hover {
  opacity: 1;
}

.fence-type {
  font-weight: 500;
  color: #303133;
  font-size: 12px;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #b3d8ff;
}

.fence-params-container {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
}

.fence-params {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
  flex: 1;
}

.fence-params:hover {
  background-color: #f5f5f5;
}

.fence-params-edit {
  flex: 1;
  background: #f9f9f9;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.params-edit-row {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.param-item label {
  font-size: 12px;
  color: #606266;
  min-width: 60px;
  font-weight: 500;
}

.params-edit-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  justify-content: flex-end;
}

.edit-params-btn {
  padding: 2px 4px !important;
  font-size: 12px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.edit-params-btn:hover {
  opacity: 1;
}

/* 围栏名称输入对话框样式 */
.name-tips {
  margin-top: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.name-tips p {
  margin: 0 0 8px 0;
  font-weight: 500;
  color: #409EFF;
}

.name-tips ul {
  margin: 0;
  padding-left: 20px;
}

.name-tips li {
  margin: 4px 0;
  color: #666;
  font-size: 13px;
  line-height: 1.4;
}

.fence-actions {
  display: flex;
  gap: 8px;
}

/* 新增的模糊搜索样式 */
.search-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1001;
  max-height: 300px;
  overflow-y: auto;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.suggestion-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.suggestion-name .highlight {
  background-color: #fff2e8;
  color: #e6a23c;
  font-weight: 600;
  padding: 1px 2px;
  border-radius: 2px;
}

.suggestion-address {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-bottom: 6px;
}

.suggestion-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.suggestion-tags .tag {
  display: inline-block;
  padding: 2px 6px;
  background: #ecf5ff;
  color: #409eff;
  font-size: 10px;
  border-radius: 2px;
  border: 1px solid #d9ecff;
}

.search-history {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 10px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.history-items {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.history-tag {
  cursor: pointer;
  transition: all 0.2s;
}

.history-tag:hover {
  background-color: #409eff;
  color: white;
}

/* 围栏表格相关样式 */
.fence-table-container {
  margin-top: 10px;
}

.fence-table-container .el-table {
  border-radius: 6px;
  overflow: hidden;
}

/* 选中行样式 */
.fence-table-container .el-table .selected-row {
  background-color: #fff2e8 !important;
}

.fence-table-container .el-table .selected-row:hover {
  background-color: #ffe8cc !important;
}

/* 围栏名称单元格 */
.fence-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.fence-name-display {
  font-weight: 600;
  color: #409EFF;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.fence-name-display:hover {
  background-color: #f0f9ff;
}

.fence-name-edit-inline {
  display: flex;
  align-items: center;
  gap: 4px;
}

.fence-name-edit-inline .el-input {
  flex: 1;
}

.fence-type-tag {
  display: inline-block;
  font-size: 11px;
  color: #909399;
  background: #f0f9ff;
  padding: 1px 6px;
  border-radius: 3px;
  border: 1px solid #d9ecff;
}

/* 坐标位置单元格 */
.location-cell {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.coordinate-item {
  display: flex;
  align-items: center;
  margin: 2px 0;
}

.coordinate-label {
  color: #909399;
  font-weight: 500;
  width: 35px;
  text-align: right;
  margin-right: 4px;
}

.coordinate-value {
  color: #303133;
  font-weight: 600;
  background: #f5f7fa;
  padding: 1px 4px;
  border-radius: 2px;
}

/* 围栏大小单元格 */
.fence-size-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.size-display {
  font-weight: 500;
  color: #606266;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
  background: #f9f9f9;
  border: 1px solid #e4e7ed;
}

.size-display:hover {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

.size-edit-inline {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.param-edit-inline {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.param-edit-inline .el-input-number {
  width: 100%;
}

.edit-actions-inline {
  display: flex;
  gap: 2px;
  justify-content: flex-end;
  margin-top: 2px;
}

.edit-actions-inline .el-button {
  padding: 2px 4px !important;
  min-width: 20px;
}

/* 操作单元格 */
.fence-actions-cell {
  display: flex;
  gap: 6px;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.fence-actions-cell .el-button {
  padding: 4px 8px !important;
  min-width: 50px;
  flex-shrink: 0;
}

/* 围栏统计信息 */
.fence-summary {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.fence-summary .el-tag {
  font-size: 12px;
}

/* 表格行悬停效果 */
.fence-table-container .el-table tbody tr:hover {
  cursor: pointer;
}

 /* 表格头部样式 */
  .fence-table-container .el-table th {
    background-color: #fafbfc;
    color: #606266;
    font-weight: 600;
  }

/* 响应式设计 */
@media (max-width: 768px) {
  .fence-table-container {
    max-height: 300px; /* 移动端降低最大高度 */
  }
  
  .fence-table-container .el-table .el-table-column {
    min-width: 120px !important;
  }

  .coordinate-item {
      flex-direction: column;
      align-items: flex-start;
    }
    .coordinate-label {
      width: auto;
      text-align: left;
    }
    .fence-actions-cell {
      flex-direction: column;
      gap: 2px;
    }
    .fence-actions-cell .el-button {
      width: 100%;
      margin: 1px 0;
      min-width: 60px;
    }
  }

/* 围栏表格滚动样式 */
.fence-table-container {
  margin-top: 10px;
  width: 100%;
  max-height: 400px;
  overflow-x: auto;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  position: relative;
  cursor: grab;
  user-select: none;
}

.fence-table-container .el-table {
  width: 100%;
  min-width: 1200px; /* 确保表格有足够宽度可以滚动，包括所有列 */
  border-radius: 6px;
}

/* 确保表格内容在滚动时正确显示 */
.fence-table-container .el-table__body-wrapper {
  overflow-x: visible;
  overflow-y: visible;
}

/* 确保固定列正确显示 */
.fence-table-container .el-table__fixed-right {
  right: 0;
}

.fence-table-container .el-table__fixed-right-patch {
  right: 0;
}

/* 防止单元格内容换行，强制水平滚动 */
.fence-table-container .el-table .cell {
  white-space: nowrap !important;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 表格头部固定样式 */
.fence-table-container .el-table thead th {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fafbfc;
}

/* 滚动条样式美化 */
.fence-table-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.fence-table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.fence-table-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.fence-table-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 滚动条交叉区域 */
.fence-table-container::-webkit-scrollbar-corner {
  background: #f1f1f1;
}

/* 确保列宽度合适 */
.fence-table-container .el-table-column {
  min-width: 120px;
}

/* 操作列固定最小宽度 */
.fence-table-container .el-table-column:last-child {
  min-width: 160px;
}
</style>